【发布时间】:2022-01-26 19:06:08
【问题描述】:
我知道已经有一些相关的问题,比如How can React useEffect watch and update state?,但我还是不完全明白。
假设我基于一个道具设置了一个index 状态;并且我需要在设置该值的任何时候对其进行清理。
<MyComponent index={4}/>
这就是我尝试的方式:
useEffect(() => {
setIndex(props.index);
}, [props.index]);
useEffect(() => {
const sanitized = sanitizeIndex(index);
setIndex(sanitized);
},[index])
const sanitizeIndex = index => {
//check that index exists in array...
//use fallback if not...
//etc.
return index
}
它不起作用(无限循环),因为状态被观察和由第二个useEffect()更新。
当然,我可以通过在 prop 上调用 sanitizeIndex() 来避免这种情况,所以我只需要 useEffect() 的单个实例:
useEffect(() => {
setIndex(sanitizeIndex(props.index));
}, [props.index]);
问题是,我在代码中多次调用setIndex,但我担心会错过使用sanitizeIndex。
还有其他方法可以“捕捉”并更新正在设置的状态值吗?
谢谢!
【问题讨论】:
-
如果您可以展示
props.index的示例(并包括index的类型:例如string/number/等)并展示sanitizeIndex的实现,你会得到更好的答案。 -
嗨@jsejcksn,我已经改进了这个问题。
标签: reactjs state use-effect