简体   繁体   中英

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. 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. 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. That's because setCountA is actually async and won't immediately change the value of 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.

In one sentence:

"State Updates are Merged"

They occur simultaneously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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