钩子中的先前状态

时间:2020-01-05 18:20:30

标签: reactjs react-hooks

类型1:

const [count, setCount] = useState(initialCount);
<button onClick={() => setCount(count + 1)}>+</button>

类型2:

const [count, setCount] = useState(initialCount);
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>

尽管以上两个代码给出的结果相同,但是它们之间到底有什么区别以及为什么第二种方法比第一种更受欢迎?

2 个答案:

答案 0 :(得分:0)

更新状态是异步的,因此当您再次更新它时,“ count”状态中可能会有先前的值

答案 1 :(得分:0)

区别在于类型2具有最新值,而类型1具有自上次刷新以来的最新值。您会注意到是否在刷新之前多次调用setCount

const [count, setCount] = useState(0);
const someFunction => () => {
   console.log(count); //0
   setCount(count + 1); // count will be set to 1 on next refresh
   console.log(count); //still 0
   setCount(count + 1); // count will still be 1  on next refresh since count hasn't been refreshed
   console.log(count); //still 0
   setCount(c => c + 1); // count will be 2 on next refresh since c has the latest value
   console.log(count); //still 0
};