【问题标题】:React Redux - Error: Invalid hook call. Hooks can only be called inside of the body of a function componentReact Redux - 错误:无效的钩子调用。 Hooks 只能在函数组件的主体内部调用
【发布时间】:2020-07-03 17:25:29
【问题描述】:

我想使用useSelector() 钩子,但我收到了上面提到的错误。我在哪里可以使用这个钩子来访问我的状态数据?

function RetrieveDataSources() {
  var dataSources = useSelector(state => state.dataSourcesReducer);
  console.log(dataSources);
}

class Data extends Component {
  constructor(props) {
    super(props);
    this.state = {
      errorMessage: false,
      isLoading: true,
      resultData: propsState && propsState.resultData,
    };


    RetrieveDataSources();
  }

 
  render() {
    return( some return code );
         }
}


export default Data;

【问题讨论】:

  • RetrieveDataSources 不是组件,它是正常功能。钩子不能以这种方式使用。

标签: reactjs redux react-redux react-hooks state


【解决方案1】:

钩子只能在函数组件或自定义钩子中调用。 您是从普通函数调用它,而不是因此出现错误。

此外,您似乎想从一个类组件中调用一个钩子——不幸的是,这并不直接得到支持。如果您必须使用类组件,请考虑使用 mapStateToProps & connect apis 从您的 redux 存储中获取它。

如果你仍然喜欢在类组件中使用钩子,here 是一个使用函数组件和 React 渲染道具与父组件共享它的示例。这通常由库完成,尽管人们无法确定调用者使用的是函数组件还是类组件。

【讨论】:

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