[英]React Redux - Error: Invalid hook call. Hooks can only be called inside of the body of a function component
I want to use the useSelector()
hook but I'm getting the error mentioned above.我想使用
useSelector()
钩子,但我收到了上面提到的错误。 Where can I use this hook to get access to my state data?我在哪里可以使用这个钩子来访问我的 state 数据?
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;
Hooks can only be called in either a function component, or custom hooks.挂钩只能在 function 组件或自定义挂钩中调用。 You are calling it from a normal function instead hence the error.
您是从普通的 function 调用它,而不是因此出现错误。
Furthermore, it seems you want to call a hook from a class component - that's unfortunately not directly supported.此外,您似乎想从 class 组件调用一个钩子 - 不幸的是,这并不直接支持。 If you have to use class components, consider using mapStateToProps & connect apis instead to get it from your redux store.
如果您必须使用 class 组件,请考虑使用 mapStateToProps & connect apis 从您的 redux 商店获取它。
If you still prefer to use hooks from within class component, here is an example to use function component and React render props to share it back with the parent component.如果您仍然喜欢在 class 组件中使用钩子, 这里是一个使用 function 组件和 React 渲染道具与父组件共享的示例。 This is usually done by libraries though where people cannot dictate whether the caller is using function component or class component.
这通常由库完成,尽管人们无法确定调用者是使用 function 组件还是 class 组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.