export default function App() {
const [count,dispatch] = useReducer((prevState)=>{
console.log('reducer')
return prevState+1
},12)
return (
<div className="App">
<h1 onClick={()=>{
console.log('dispatch-start')
dispatch()
console.log('dispatch-end')
}}>Hello CodeSandbox{count}</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
- 在react17中点击h1第一次会打印
dispatch-start
reducer
dispatch-end
reducer - 如果再次点击h1会打印
dispatch-start
dispatch-end
reducer - 如果在react18中每次打印出的都是
dispatch-start
dispatch-end
reducer
这是什么原因呢?
Reactjs的懒计算、立即计算策略。详细参考解密React state hook