Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React useState rerender触发器的行为因其调用时间而异_Reactjs - Fatal编程技术网

Reactjs React useState rerender触发器的行为因其调用时间而异

Reactjs React useState rerender触发器的行为因其调用时间而异,reactjs,Reactjs,假设您有一个具有多个useState的钩子,例如: 函数useMyHook(){ const[s1,setS1]=useState(); const[s2,setS2]=useState(); const setFn=useCallback( () => { console.log('set s1'); setS1(Date.now()); console.log('set s2'); setS2(Date.now()); }, [setS1,setS2] ); 返回setFn; } 现在,根

假设您有一个具有多个useState的钩子,例如:

函数useMyHook(){
const[s1,setS1]=useState();
const[s2,setS2]=useState();
const setFn=useCallback(
() => {
console.log('set s1');
setS1(Date.now());
console.log('set s2');
setS2(Date.now());
},
[setS1,setS2]
);
返回setFn;
}
现在,根据您何时调用
setFn
react将触发一个或两个重新渲染器

  • 一个重招标人:
函数MyComponent(){
console.log('render')
const setTwoStates=useMyHook()
//同步调用=>只触发一次重新渲染
useEffect(()=>SetTwoState(),[]))
//console.log是:渲染、设置s1、设置s2、渲染
返回(
你好
);
}
  • 两个重招标人:
函数MyComponent(){
console.log('render')
const setTwoStates=useMyHook()
//在稍后的勾选中调用setFn后,react将触发两次重新渲染
useEffect(()=>setTimeout(setTwoState,1),[]))
//console.log是:渲染、设置s1、渲染、设置s2、渲染
返回(
你好
);
}
有人对此有解释吗?这可能导致意外行为,具体取决于如何调用钩子

我还创建了一个小的示例存储库,以防您想使用它


当批处理状态设置程序在useEffect回调或事件处理程序中设置状态时(函数运行时),它们将作出反应,但在异步示例中,状态是在effect函数返回后设置的

constsyncfn=()=>
console.log('in sync function');
const asyncFn=()=>setTimeout(
()=>console.log('in async function'),
10
);
syncFn();
log('sync函数返回');
异步fn();

log('async function returned')thx,这很有意义!我刚刚找到的一篇相关文章/答案