我想知道 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/