[英]PrevState does not update state value immediately in React JS
我正在嘗試使用 prevState 立即更新狀態值,但值不會改變。 我知道 seState 是異步函數,但是如果我使用 prevState,不應該立即更新嗎? 我在哪里做的錯誤?
count: 0
this.setState((prevState) => ({
count: prevState +1
}));
console.log(this.state.count+" count")
如您所知,setState 是異步的。 但也要了解如果您在 setstate 中傳遞回調,那么您需要調用prevState.something
作為something is your state
。 所以基本上你需要這樣做:
this.setState(
(prevState) => ({
count: prevState.count + 1
}),
() => {
console.log(this.state.count + " count");
}
);
這是POC:
import React from "react";
import "./styles.css";
class Test extends React.Component {
state = {
count: 0
};
handleClick = () => {
this.setState(
(prevState) => ({
count: prevState.count + 1
}),
() => {
console.log(this.state.count + " count");
}
);
};
render() {
return (
<>
{this.state.count}
<button onClick={this.handleClick}>Click </button>
</>
);
}
}
export default function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Test />
</div>
);
}
這是演示: https : //codesandbox.io/s/serene-beaver-cu4bl?file=/ src/App.js: 0-596
好的,您必須了解以下內容
function foo() {
this.setState((prevState) => ({
count: prevState + 1,
}));
}
//call function first and then log
foo()
console.log(count) // here you will get your answer
記住一個父函數中的任意數量的 this.setState 語句會在父函數結束后執行
它應該是 prevState.count + 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.