首页 > 解决方案 > 加载 Solid webId 配置文件时出现 React Hook 错误

问题描述

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

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

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

标签: reactjsreact-hookssolid

解决方案


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

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

  • 使用 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);

推荐阅读