【发布时间】:2019-11-05 07:45:46
【问题描述】:
当useEffect钩子的依赖改变时,useEffect钩子的效果函数仅在渲染周期(more discussed here)之后被调用。这经常会造成 UI 因组件模型不一致而变得不一致的情况。
这是一个简单的示例,其中useEffect 用于根据inputValue 的值运行resultValue 的计算:
function App() {
const [inputValue, incrementInputValue] = useReducer((s, _) => s + 1, 0);
const [resultValue, setResultValue] = useState(0);
useEffect(() => {
// It could be an asynchronous call to business logic etc.
setResultValue(inputValue * 2);
}, [inputValue]);
console.log("Render: %d * 2 = %d", inputValue, resultValue);
return (
<div className="App">
<p>{inputValue} * 2 = {resultValue}</p>
<button onClick={() => { console.log('Click'); incrementInputValue(undefined); }}>
Increment
</button>
</div>
);
}
此代码返回以下日志:
Render: 0 * 2 = 0
Click
Render: 1 * 2 = 0 // inputValue was updated, but useEffect not called yet
Render: 1 * 2 = 2
Click
Render: 2 * 2 = 2 // inputValue was updated, but useEffect not called yet
Render: 2 * 2 = 4
避免由于延迟调用 useEffect 引起的这种不一致的最佳方法是什么?
【问题讨论】:
标签: reactjs react-hooks