[英]abort state set with React useState hook function call
With the old class-based this.setState()
method, we could return null
from a function passed to setState
to tell React not to do anything with that specific setState
call:使用旧的基于类的
this.setState()
方法,我们可以从传递给setState
的 function 返回null
以告诉 React 不要对特定的setState
调用执行任何操作:
this.setState(({ value }) => {
if (value === 0) {
return null;
} else {
return { value: value - 1 };
}
});
I'm trying to understand what's the correct way to do this with React Hooks, is the below correct?我试图了解使用 React Hooks 执行此操作的正确方法是什么,以下是否正确?
const [x, setValue] = useState(0);
setValue(value => {
if (value === 0) {
return value;
} else {
return value - 1;
}
});
I'm trying not to trigger a re-render if I pass the original value.如果我通过原始值,我会尽量不触发重新渲染。
Looks like a job for useEffect
hook:看起来像是
useEffect
挂钩的工作:
useEffect(() => {
setValue(value => {
if (value === 0) {
return value;
} else {
return value - 1;
}
});
}, [x])
Effect will only run if x
changes.仅当
x
更改时才会运行效果。
React shouldn't rerender. React 不应该重新渲染。 From react docs ( https://reactjs.org/docs/hooks-state.html ): "If your update function returns the exact same value as the current state, the subsequent rerender will be skipped completely."
From react docs ( https://reactjs.org/docs/hooks-state.html ): "If your update function returns the exact same value as the current state, the subsequent rerender will be skipped completely."
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.