【问题标题】:React Hook error when loading Solid webId profile加载 Solid webId 配置文件时出现 React Hook 错误
【发布时间】:2021-05-31 14:12:16
【问题描述】:

我正在尝试使用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.

【问题讨论】:

  • 将此组件转换为functional component。因为useLDflex 是一个自定义的钩子,而钩子只在函数内部使用
  • 已解决。使用 HOC 的解决方案在此处发布:stackoverflow.com/questions/66467419/…

标签: reactjs react-hooks solid


【解决方案1】:

你不能在类组件中使用 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);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2012-11-21
  • 2020-04-13
  • 2021-05-01
  • 1970-01-01
  • 2019-02-16
  • 1970-01-01
  • 2021-09-02
  • 1970-01-01
相关资源
最近更新 更多