如何使用 useStore、useSelector、useDispatch 钩子?

问题描述:

Redux 7.1.0 版发布了新的钩子.我不明白如何在实践中使用这些钩子.有人可以举例说明如何使用这些钩子吗?

New hooks have been released with Redux version 7.1.0. I don't understand how to use these hooks in practice. Can someone give an example of how to use these hooks?

请看sample.

  • useSelector 就像 mapStateToProps,你从 store 中选择属性,当 store 改变时组件会更新

  • useSelector is like mapStateToProps, you select properties from store and component is updated when store is changed

useDispatch 只是返回 dispatch.就像用空的第二个参数调用 connect() 一样.

useDispatch is just returning dispatch. It like calling connect() with empty second argument.

useStore 用于检索store.但是这种存储访问只能用于存储操作,例如reducer 替换.当 store 发生变化时,以这种方式访问​​ store 的组件不会更新.

useStore is used to retrieve store. But such store access can only be used for store manipulation, like reducer replacement. When store is changed, component which access store this way is not updated.

单击上面示例中的 Check2 按钮,直到您单击更新我"按钮后才会检查 check2

Click Check2 button in example above and check2 is not checged untill you click 'update me' button