作者:判官-包公_529 | 来源:互联网 | 2023-09-18 00:35
我有2种状态,一种是从API响应设置的,另一种是在API响应更改特定阈值时设置的,并在超时后将其清除,我使用钩子来实现相同的状态。
所以我想知道哪种方法更好
const [data,setData] = useState();
const [thresholdChanged,setThresholdChanged] = useState();
// I clear thresholdChanged message after 5 seconds
useEffect(() => {
if(thresholdChanged !== undefined) {
const timeout = setTimeout(() => setThresholdChanged(undefined),TIMEOUT)
return () => clearTimeout(timeout);
}
return undefined;
},[thresholdChanged])
现在设置数据我有2个选项
第一个永远不会重新创建update
方法,而是在第一个setter中调用另一个setter,这是有效的模式吗?
const update = useCallback((newData) => {
setData((currentData) => {
if(currentData SOME_VALUE) {
setThresholdChanged(true)
}
return newData;
})
},[])
或者我应该选择第二种方法,它每次数据更新时都会重新创建方法
const update = useCallback((newData) => {
if(data SOME_VALUE) {
setThresholdChanged(true)
}
setData(newData)
},[data])
哪种方法更好?为什么?
注意:简化了询问问题的代码。
您应该选择选项#1的原因有两个:
const update = useCallback((newData) => {
setData((currentData) => {
if(currentData SOME_VALUE) {
setThresholdChanged(true)
}
return newData;
})
},[])