【问题标题】:React functional (hooks) component in parent class component在父类组件中反应功能(钩子)组件
【发布时间】:2021-09-01 10:07:56
【问题描述】:

我有一个相当大的 React 组件 SearchProvider 编写为一个类和一个 UI 组件 InputRange 我使用 Hooks 作为函数组件编写。

ATM 我收到错误“无效的钩子调用。只能在函数组件的主体内部调用钩子。”

我可以将钩子组件用作类组件的子组件吗?

import { InputRange } from 'react-components';

class SearchProvider extends Component {
  render() {
    return <Fragment>
        <InputRange />
        {this.props.children}
      </Fragment>;
  }
function InputRange(props) {
   ...
   useEffect(_ => { ...});
   return <div className="input-range"></div>;
}

【问题讨论】:

  • 这看起来很奇怪。它看起来像是功能组件的有效代码
  • 正是@Phoenix1355 应该没有问题。
  • @edo 能否提供 InputRange 组件的完整代码。
  • @Phoenix1355 @mosh 很酷,这是可能的......你说得对,它在沙箱中工作 codesandbox.io/s/wild-darkness-xlti3?file=/src/App.js 不过我有一个更复杂的设置,InputRange 在不同的存储库中并包含作为 npm 包。 SearchProvider 也使用 Redux。这会是个问题吗?
  • @edo 这很难说。我不相信 Redux 可能是问题的原因。但如果 InputRange 在另一个 repo 中,这可能是个问题。但同样,这很难说,因为它取决于 npm 包设置等。 NPM 包是公共库还是您自己制作的?

标签: javascript reactjs react-hooks react-component


【解决方案1】:

我回答我自己的问题。问题是重复反应,与钩子没有直接关系。见https://reactjs.org/warnings/invalid-hook-call-warning.html#duplicate-react

我必须在 UI 组件中将 reactreact-dom 声明为 peerDependencies。这样就解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-22
    • 2020-11-30
    • 1970-01-01
    • 2021-07-17
    • 2020-09-17
    • 2019-09-23
    • 2020-09-05
    • 2020-03-12
    相关资源
    最近更新 更多