reactjs - React JS 和 Redux : useSelector() vs useStore()

标签 reactjs redux

我想知道 useSelector 和 UseStore 之间有什么区别。使用一种代替另一种有什么好处吗?谢谢。

使用选择器

  const { pages } = useSelector((state: RootState) => {
    return {
      pages: state.pages
    };
  });
  console.log(pages);

useStore
  const pageArrayTwo = useStore();
  const pageArray = pageArrayTwo.getState().pages;
  console.log(pageArray);

两种情况下的输出相同
[{…}]
0: {id: 1, title: "Use Redux", content: "Welcome"}
length: 1
__proto__: Array(0)

最佳答案

UseSelector,这里的主要优点是它对之前的选择器结果进行了浅层比较,因此如果结果相同,则可能不会重新渲染。

When an action is dispatched, useSelector() will do a reference comparison of the previous selector result value and the current result value. If they are different, the component will be forced to re-render. If they are the same, the component will not re-render.


useStore只是让您访问商店对象,基于访问商店状态的任何组件逻辑都不会从此检查中受益。事实上,redux 甚至建议不要为此目的使用它。

This hook should probably not be used frequently. Prefer useSelector() as your primary choice. However, this may be useful for less common scenarios that do require access to the store, such as replacing reducers.

关于reactjs - React JS 和 Redux : useSelector() vs useStore(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61292433/

相关文章:

html - 如何在 react js中将类型数据缓冲区转换为图像

ReactJS 获取渲染组件高度

javascript - 如何测试使用来自已分派(dispatch)操作的数据的 Saga

javascript - 如何使用 Redux 时间旅行来处理错误

javascript - 状态改变后调用方法

javascript - 解开 onMouseEnter、onMouseLeave 和 onClick 中的状态变化

javascript - Next.js 中的动态嵌套路由

javascript - 如何使用 React-bootstrap 进行多输入表单验证?

reactjs - 如何在 React/Redux 应用程序的任何(重新)渲染后触发事件

javascript - 如何使用 ReactJS、Redux 和 ES2015 将 onChange 回调正确绑定(bind)到 'this'?