【问题标题】:previous state in hooks钩子中的先前状态
【发布时间】:2020-01-05 18:20:30
【问题描述】:

类型 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>

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

【问题讨论】:

标签: reactjs react-hooks


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    不同之处在于类型 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
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-28
      • 1970-01-01
      • 2020-05-23
      • 2021-10-04
      • 1970-01-01
      相关资源
      最近更新 更多