若在设置值之后调用React useState(),则不会更新变量的值。
我读过useEffect(),但不知道它对这个特定场景有什么用处。
完整代码(请打开控制台选项卡以查看变量状态)
// hook
const [ error, setError ] = useState<boolean>();
const handleSubmit = (e: any): void => {
e.preventDefault();
if (email.length < 4) {
setError(true);
}
if (password.length < 5) {
setError(true);
}
console.log(error); // <== still false even after setting it to true
if (!error) {
console.log("validation passed, creating token");
setToken();
} else {
console.log("errors");
}
};
假设用户没有有效的凭据。问题就在这里:
if (email.length < 4) { // <== this gets executed
setError(true);
}
if (password.length < 5) { // <== this gets executed
setError(true);
}
console.log(error); // <== still false even after setting it to true
if (!error) { // <== this check runs before setError(true) is complete. error is still false.
console.log("validation passed, creating token");
setToken();
} else {
console.log("errors");
}
您正在使用多个独立运行的if检查,而不是使用单个if检查。您的代码执行所有if检查。在一次检查中,当其中一个条件通过时,调用< code>setError(true),但是< code>setError()是异步的。在调用下一个if-check之前,该操作不会完成,这就是为什么它看起来好像您的值从未被保存过。
你可以用if-else和useEffect的组合来更干净地做到这一点:https://codesandbox.io/s/dazzling-pascal-78gqp
import * as React from "react";
const Login: React.FC = (props: any) => {
const [email, setEmail] = React.useState("");
const [password, setPassword] = React.useState("");
const [error, setError] = React.useState(null);
const handleEmailChange = (e: any): void => {
const { value } = e.target;
setEmail(value);
};
const handlePasswordChange = (e: any): void => {
const { value } = e.target;
setPassword(value);
};
const handleSubmit = (e: any): void => {
e.preventDefault();
if (email.length < 4 || password.length < 5) {
setError(true);
} else {
setError(false);
}
};
const setToken = () => {
//token logic goes here
console.log("setting token");
};
React.useEffect(() => {
if (error === false) {
setToken();
}
}, [error]); // <== will run when error value is changed.
return (
<div>
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="email@address.com"
onChange={handleEmailChange}
/>
<br />
<input
type="password"
placeholder="password"
onChange={handlePasswordChange}
/>
<br />
<input type="submit" value="submit" />
</form>
{error ? <h1>error true</h1> : <h1>error false</h1>}
</div>
);
};
export default Login;
与< code>setState一样,< code>useState是异步的,倾向于批量更新,以提高性能。使用< code>useEffect是正确的,它允许您在状态更新后有效地执行回调。
文档中的示例:
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
尽管我们也建议,如果在请求状态更新时需要更新的值,那么最好在组件中只包含一个变量。
有关同步使用状态的详细信息
如果您熟悉Redux的减速机,您可以使用use Reduce er
作为另一种选择。来自文档:
useReducer 通常比 useState 更可取,当您具有涉及多个子值的复杂状态逻辑时,或者当下一个状态依赖于前一个状态时。useReducer 还允许您优化触发深度更新的组件的性能,因为您可以向下传递调度而不是回调。