[英]React useState not updating value in async function
const Login = () => {
const [data, setData] = useState({
name: "",
email: "",
password: ""
});
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(""); // set empty error state
const handleChange = event =>
setData({ ...data, [event.target.name]: event.target.value });
const handleSubmit = async event => { // async function to handle submit
event.preventDefault();
try {
setIsLoading(true);
const response = await axios.post( // response from server
"http://localhost:5000/api/users/signup",
JSON.stringify(data),
{
headers: {
"Content-Type": "application/json"
}
}
);
console.log(response.data); // data comes back fine
setIsLoading(false);
} catch (err) {
const message = err.response.data.message;
setError(message); // set error message if there is an error
setIsLoading(false); // always successfully setLoading to false
console.log(isLoading); // result is false
console.log(message); // result message
console.log(error); // result is still empty string. state never updated with message
}
};
我似乎無法弄清楚為什么錯誤狀態沒有在 catch 塊中更新。 我總是收到消息並且可以記錄消息,但狀態永遠不會更新到消息。 我注意到如果我在第二次提交時多次提交表單,狀態會更新。
任何幫助表示贊賞。
對於任何副作用,如網絡調用,數據更新本質上是異步的。 你必須使用useEffect 。 這將解決問題。 要重用邏輯,您可以創建自定義鈎子。 查看示例:自定義鈎子
使用效果:
useEffect(
() => {
const subscription = props.source.subscribe();
return () => {
subscription.unsubscribe();
};
},
[props.source],
);
自定義掛鈎:
function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
return () => {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.