[英]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.