[英]React onSubmit wait for async IIFE inside the function to update state with hooks
[英]Changing state inside async function in React
考虑以下场景:
const ExampleComponent = () => {
const [status, setStatus] = useState(500)
//Calling this function with a click event
const submitHandler = () => {
const url = 'localhost:8000/foo'
fetch(url)
.then((res) => {
setStatus(res.status)
return res.json()
})
.then((res) => {
if (status === 200) {
console.log("OK")
} else {
console.log("Something went wrong")
}
})
}
}
在这种情况下,由于 React 将 setStatus 任务排队,所以当我进行status === 200
检查时,状态尚未更新。 那么我们如何解决这种情况呢?
当然它会打印(“出了点问题”)。 因为您的组件尚未更新。 为了检查你的答案。 运行此代码并查看您的控制台以了解更多信息:
import React, { useState } from 'react';
const App = () => {
const [status, setStatus] = useState(500);
const submitHandler = () => {
const url = 'https://www.irdevprogs.ir/api/tsetmc/companies'
fetch(url)
.then((res) => {
setStatus(res.status)
return res.json()
})
.then((res) => {
console.log(status)
if (status === 200) {
console.log("OK")
} else {
console.log("Something went wrong")
}
})
}
return (
<div>
<button onClick={submitHandler}>first</button>
<button onClick={()=> console.log(status)}>second</button>
</div>
);
};
export default App;
但是解决方案是什么:React 库的标准例程说您不能 setState 并使用更新的 state 并发。 你应该使用 useEffect 钩子来处理这个。 并将状态添加到依赖数组以处理这种情况。 像这样的东西:
useEffect(() => {
if (status === 200) {
console.log("OK")
} else {
console.log("Something went wrong")
}
}, [status])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.