加载 Solid webId 配置文件时 React Hook 错误

问题描述

我正在尝试使用 Solidreact-components 从他们的 webId 加载用户的个人资料。我遇到了 useLDflex() 的问题。问题似乎与 React Hooks 有关,但我无法弄清楚。我的目标是在页面加载时加载用户的个人资料;愿意做出任何必要的改变。我使用 MobX 作为状态。

下面是代码,下面是编译器/网络浏览器中的错误。谢谢。

代码(React/JSX/TypeScript):

    import React from 'react';    // 16.14.0
    import { observer } from 'mobx-react';
    import { observable } from 'mobx';
    import { useLDflex } from '@solid/react';    // 1.10.0

    @observer
    export class Profile extends React.Component<{profileId: string},{}> {
        @observable webId = `https://${this.props.profileId}.solidcommunity.net/profile/card#me`;
        @observable name = useLDflex(`[${this.webId}`)[0];

        render() {
            return (
                <main role="Profile">
                    <div className="container">
                        webId: https://{this.props.profileId}.solidcommunity.net/profile/card#me
                        Name: {this.name}
                    </div>
                </main>
            )
        }
    }

错误

src/components/profile/index.tsx
  Line 9:24:  React Hook "useLDflex" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function  react-hooks/rules-of-hooks

Search for the keywords to learn more about each error.

解决方法

你不能在类组件中使用 React Hooks,参考这里:https://reactjs.org/docs/hooks-faq.html#should-i-use-hooks-classes-or-a-mix-of-both

所以你需要用 Mobx 将其重写为 functional component,或者制作一个 higher order component 并将 props 传递到你的类组件中(当你的类太复杂而无法重写时)

  • 使用 FC:
import {observer} from "mobx-react";

const Profile = observer(({ profileId }) => {
  // ...
  const name = useLDflex(`...`);
  // ...
})
  • HOC
const withName = (Component) => ({ profileId }) => {
  const name = useLDflex('...');
  return <Component name={name} profileId={profileId} />
}
export default withName(Profile);

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...