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

React Hook error when loading Solid webId profile

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

下面是代码,下面是 compiler/web 浏览器中的错误。谢谢。

代码(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.

您不能在 class 组件内使用 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 并将道具传递到你的 class 组件中(当你的 class 太重写复杂)

  • 有 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);