简体   繁体   English

我不知道为什么 state 会这样更新?

[英]I have no idea why state updated like this?

I just know that when using useState 's state is updated, fired component and its child components are also re-render.我只知道使用useState的 state 时更新,触发组件及其子组件也重新渲染。 But when wrote this code, somehow update like this console log.但是当写下这段代码时,不知何故会像这个控制台日志一样更新。

import { useState } from 'react';
import logo from './logo.svg';
import './App.css';
import { ChildA } from './ChildA.jsx';
import { ChildB } from './ChildB.jsx';


function App() {
  console.log('Parent render!')
  const [countA, setCountA] = useState(0);
  const [countB, setCountB] = useState(0);

  const asyncJustReturnNull = async () => {
    return null;
  }

  const countUpDouble = () => {
    setCountA(countA + 1);
    asyncJustReturnNull().then(() => {
      setCountA(countA + 1);
      setCountB(countB + 1);
    })
  }

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <button onClick={() => countUpDouble()}>
          Update A and B at the same time.
        </button>
        <ChildA />
        countA is {countA}
        <ChildB />
        countB is {countB}
      </header>
    </div>
  );
}

export default App;

在此处输入图像描述

CodePen is below. CodePen 如下。 https://codepen.io/showgotagami/pen/qBaBveG https://codepen.io/showgotagami/pen/qBaBveG

Because when you call因为当你打电话

setCountA(countA + 1);
justReturnNull().then(() => {
    setCountA(countA + 1);
    setCountB(countB + 1);
})

countA is going to have the same value (0 initially) both times it's called. countA时,它的值都相同(最初为 0)。 That's because setCountA is actually async and won't immediately change the value of countA .那是因为setCountA实际上是异步的,不会立即改变countA的值。

A way of better visualising this could be this:一种更好地可视化的方法可能是这样的:

const incrementA = () => {
    console.log(countA);
    setCountA(countA + 1);
}

const updateBoth = () => {
    incrementA();
    justReturnNull().then(() => {
        incrementA();
        setCountB(countB + 1);
    })
};

This way we no longer pass countA around.这样我们就不再传递countA了。

In one sentence:一句话:

"State Updates are Merged"

They occur simultaneously.它们同时发生。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM