我正在尝试在触发器后更新状态,并希望立即使用该状态来触发函数,但状态没有立即更新。
有什么建议吗?
<Button
onClick={() => {
console.log(finalData) //old data
setFinalData(mutableData); // updating state
console.log(finalData) // still geeting old state
}>
</Button>
setFinalData
是一种异步行为,所以如果你:
console.log(finalData) //old data
setFinalData(mutableData); // <----- async behavior
console.log(finalData) // you will never get updated finalData directly here
解决方案 :useEffect
useEffect(() => {
// you will get updated finalData here, each time it changes
console.log(finalData);
// you can trigger your function from here
},[finalData]);
这是代码片段,希望这会消除您的疑虑:
const { useState , useEffect } = React;
const App = () => {
const [finalData,setFinalData] = useState([]);
useEffect(() => {
setTimeout(() => {
setFinalData([...finalData, "Vivek" , "Darshita"]);
console.log("finalData -----> not updated right after" ,finalData);
},2000);
},[]);
useEffect(() => {
if(finalData.length)
console.log("Final data updated , invoke your function" , finalData)
},[finalData]);
return (
<div>
{ finalData.map(user => <p>{user}</p>) }
</div>
);
}
ReactDOM.render(<App />, document.getElementById('react-root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react-root"></div>