是否可以覆盖 React 的 useState、useMemo、useEffect 钩子的相等函数?
假设我有这样的代码:
const [obj, setObj] = useState({ value: 0 });
// somewhere else
setState({value: 0});
// somewhere else
const value = useMemo(() => obj.value, [ obj ]);
// somewhere else
useEffect(() => { console.log(obj.value) }, [ obj ] );
是否可以有类似的东西:
const [ obj, setObj ] = useStateWithSelector(obj, (prev, next) => prev.value === next.value);
所以我可以告诉反应仅当 equalFunction
(prev, next) => prev.value === next.value
返回 false 时才重新渲染?
Assume I have this code:
const [obj, setObj] = useState({ value: 0 });
// somewhere else
setState({value: 0});
// somewhere else
const value = useMemo(() => obj.value, [ obj ]);
// somewhere else
useEffect(() => { console.log(obj.value) }, [ obj ] );
Is it possible to have something like:
const [ obj, setObj ] = useStateWithSelector(obj, (prev, next) => prev.value === next.value);
So I can tell react to rerender only if the equalityFunction
(prev, next) => prev.value === next.value
return false ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
react 建议的习惯用法
解决方案是不要使用复杂的数据类型(如对象或数组)作为 React 效果的依赖项。使用
[obj.value]
而不是[obj]
。来自 useEffect 文档:
Run 下面的代码示例,输入一个值并单击 Set 几个次。请注意,仅当在输入中键入新值时状态才会更改。
自定义挂钩解决方案
如果您必须使用
[obj]
作为依赖项,您可以像您建议的那样编写useStateWithGuard
自定义挂钩。运行下面的代码示例,输入一个值并单击设置几次。
[obj]
用作依赖项,但状态仅在新值通过防护时才会更改。react suggested idiom
The solution is not to use complex data types like Object or Array as dependencies for React effects. Use
[obj.value]
instead of[obj]
.From the useEffect docs:
Run the code example below, enter a value and click Set several times. Notice the state is only changed when a fresh value is typed in the input.
custom hook solution
If you must use
[obj]
as a dependency, you could write auseStateWithGuard
custom hook like you suggested.Run the code example below, enter a value and click Set several times.
[obj]
is used as a dependency but the state only changes when the new value passes the guard.