本文介绍了如何在类组件中使用 react-redux useSelector?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 React 新手,正在尝试学习 redux.我想访问类中的商店,但它给了我一个错误,我不能在类中使用钩子.

I am new in react and trying to learn redux. I want to access the store inside a class, but it gives me an error the I cant use hook in class.

当我在函数中使用此代码时(正如我在 YouTube 教程中看到的那样),它可以正常工作.在这里,我可以访问商店的柜台.

When I use this code in function (as I saw in a YouTube tutorial), it works without any problem. Here I access to counter in the store.

 function App() {
      const counter = useSelector(state => state.counter);

      return <div>{counter}</div>;
    }

但是当我想在课堂上这样做时,它给了我一个错误,我不能在课堂上使用钩子.

but when I want to do this in class, it gives me an error that I can't use hooks in class.

那么如何在类组件中使用 useSelector 或 useDispatch 访问我的商店?

So how can I access to my store either useSelector or useDispatch in class component?

推荐答案

正如@Ying Zuo所说,你的方法只适用于函数组件.

as @Ying Zuo said, your method works only with function components.

用于解决此特定问题:

而不是这一行:

const counter = useSelector(state => state.counter);

您可以像这样定义计数器状态:

you define the counter state like this:

const mapStateToProps = state => ({
  counter: state.counter
});

那么对于调度,您应该像这样使用它:

then for dispatching you should use it like this:

const mapDispatchToProps = () => {
  return {
    increment, decrement

  };
};

最后你把所有的东西都这样组合起来:

at the end you combine everything like this:

export default connect(
  mapStateToProps,
  mapDispatchToProps()
)(App);

不要忘记从 action 导入{increment, decrement}"和从 react-redux 模块导入connect"

and dont forget to import "{increment, decrement}" from your action and "connect" from react-redux module

有关详细信息,很好的 youtube 视频(在我看来):

for more information, good youtube video that explains it very well (in my opinion):

https://www.youtube.com/watch?v=9d020AQCtcU

这篇关于如何在类组件中使用 react-redux useSelector?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 16:17