如何用createSelector()记忆useElector()?
我想在我的编程网站上解释redux商店的回忆。
我现在拥有的:
import { useCallback, useMemo, memo } from "react";
import { useSelector, useDispatch } from "react-redux";
import { createSelector } from "reselect";
const Plus = memo(({ onIncrement }) => {
console.log("rendering <Plus>...");
return <button onClick={onIncrement}>+</button>;
});
export default () => {
console.log("rendering <App>...");
const v = useSelector((state) => {
console.log("useSelector() invoked");
return state;
});
const dispatch = useDispatch();
const increment = useCallback(() => dispatch({ type: "INCREMENT" }), [
dispatch
]);
return (
<div>
<span>{v}</span>
<Plus onIncrement={increment} />
</div>
);
};
如您所见,我已经成功地记住了用usecallback()记住dispatch()函数。但是,每次单击按钮时,useselector()被调用两次。
有没有办法只称其为一次?我正在考虑使用“ Reselect”库中的CreateSelector()记忆。我不明白那个库。有人可以提供一些指导吗?
参考:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
他们通过将选择器运行2次来正常工作。如果您还将选择器内部的状态(计数器)打印出来,将会更容易,更明显。
参考: https://reaect-react-react-react-react-react-react.js.ss.org/ API/钩子#Equality-Comparisons and-updates
事情将是这种方式:
They are working correctly by having running the selectors 2 times. It would be easier and more obvious if you also print out the state (the counter) inside the selector.
Reference: https://react-redux.js.org/api/hooks#equality-comparisons-and-updates
Things will be this way: