【问题标题】:React hooks inside a curry function (creating a HOC) returning an error from linter 'React Hook "useContext" cannot be called inside a callback'curry 函数中的 React 钩子(创建一个 HOC)从 linter 'React Hook“useContext”不能在回调中调用'返回错误
【发布时间】:2020-06-18 17:25:35
【问题描述】:

在我的项目中,我摆脱了类,只使用 Hooks。现在我正在尝试创建一个 HOC,我的 linter 在我的 curry 函数中使用 Hooks 返回一个错误。这是我的代码的简化版本:

const myCurryFunction = WrappedComponent => props => {
  const [state, setState] = React.useState();
  return <WrappedComponent {...props} />
}

完整的 eslint 错误是这个:

React Hook "useState" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function.

有什么线索吗?我真的很感激任何建议

【问题讨论】:

  • 钩子必须在我们组件的顶层调用reactjs.org/docs/hooks-rules.html
  • 接下来,我倾向于认为我们不能在这种 HOC 模式中使用钩子:/
  • 可以用自定义钩子完成吗?
  • 你是什么意思@JosephD.?要将我的所有逻辑移动到自定义钩子中,然后在我的 curry 函数中使用它?如果是的话,我不这么认为。如果钩子之所以抱怨是因为它们必须在顶部,那是因为否则会给执行顺序带来错误。

标签: reactjs react-hooks currying high-order-component react-hoc


【解决方案1】:

两种选择。

  1. Respect the rules of hooks,修改你的代码。

    const myCurryFunction = WrappedComponent => 功能比较(道具){ const [状态,setState] = React.useState(); 返回 }

  2. 关闭源文件的 lint。

【讨论】:

    【解决方案2】:

    我发现了这个 github 问题: https://github.com/facebook/react/issues/20531

    HOC 模式应该可以工作,但非常具体。

    【讨论】:

      猜你喜欢
      • 2019-10-22
      • 2021-04-03
      • 2021-06-19
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 2023-03-21
      相关资源
      最近更新 更多