【发布时间】:2020-11-19 00:43:11
【问题描述】:
我正在使用 React,但我遇到了状态问题,因为它不会立即更新。我知道以前有人问过这个问题,但我在处理异步和等待时也遇到了麻烦。它似乎也不起作用(也许我没有把它放在正确的地方)。
我有一个表单,它会在更新状态中的错误之前登录
这里是代码
import React, { useState } from "react";
function App() {
const [errorName, setErrorName] = useState(false);
const [errorPassword, setErrorPassword] = useState(false);
const handleSubmit = (e) => {
e.preventDefault();
if (!e.target[0].value) {
setErrorName(true);
}
if (!e.target[1].value) {
setErrorPassword(true);
}
if (!errorName && !errorPassword) {
alert("You have logged in succesfully!");
}
};
return (
<div className="App">
<header className="App-header">
<form onSubmit={handleSubmit}>
<input placeholder="enter your name" />
<p style={errorName ? { display: "block" } : { display: "none" }}>
You have not entered your name
</p>
<input placeholder="enter your password" />
<p style={errorPassword ? { display: "block" } : { display: "none" }}>
You have not entered your password
</p>
<button type="submit"> Submit</button>
</form>
</header>
</div>
);
}
export default App;
【问题讨论】:
标签: reactjs asynchronous use-state