javascript - useSelector 状态返回 undefined 但 redux 开发工具显示该值
问题描述
我从 api 获取数据,然后将一些细节存储在 redux 存储中,从 redux 存储我在浏览器本地存储上设置一些值。
我正在使用浏览器本地存储作为条件语句,但是由于 redux 存储中的未定义或初始状态,我的条件没有执行。
我的代码:
const Login = () => {
const dispatch = useDispatch();
const { isAuth } = useSelector((state) => state.login);
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const submitLoginForm = async (e) => {
e.preventDefault();
dispatch(loginPending());
const response = await fetch("https://localhost:44316/api/auth/login", {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
credentials: 'include',
body: JSON.stringify({
email,
password,
})
});
if(response.status === 200){
dispatch(loginSuccess());
debugger;
localStorage.setItem('auth',isAuth);
console.log(isAuth);
console.log(localStorage.getItem('auth'));
}
else{
dispatch(loginFailed());
}
};
if(JSON.parse(localStorage.getItem('auth')) === true){
return <Redirect to="/" />
}
return (
<React.Fragment>
<Navbar />
<div className="formContainer">
<h1>Login</h1>
<form className="loginForm" onSubmit={submitLoginForm}>
<div className="mb-3">
<label htmlFor="exampleInputEmail1" className="form-label">
Email address
</label>
<input
type="email"
className="form-control"
aria-describedby="emailHelp"
onChange={(e) => setEmail(e.target.value)}
/>
<div id="emailHelp" className="form-text">
We'll never share your email with anyone else.
</div>
</div>
<div className="mb-3">
<label htmlFor="exampleInputPassword1" className="form-label">
Password
</label>
<input
type="password"
className="form-control"
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<button type="submit" className="btn btn-primary">
Login
</button>
</form>
</div>
</React.Fragment>
);
};
我的切片包含:
loginSuccess: (state) => {
state.isLoading = false;
state.isAuth = true;
state.error = "";
}
我想从 redux 存储中获取 isAuth 值,然后将其存储在浏览器本地存储中。但我false
在控制台中获得了价值
在浏览器 redux 开发工具中,它显示了状态变化。
解决方案
推荐阅读
- laravel - 使用 laravel 构建 Docker - SQLSTATE[HY000] [2002]
- security - 为什么要刷新令牌而不是长期访问令牌?
- javascript - 在浏览器中直接对 S3 URI 执行 GET 时如何从 AWS 读取二进制数据响应?
- generator - 生成对抗网络中生成器的每一层会发生什么?
- javascript - 我想从函数中访问一个变量
- sql-server - 如何查询嵌套
和 - a里面的标签
SQL Server XML 列中的节点? - java - Java 尝试捕获异常
- macos - PATH 变量中的自定义路径在 Mac 上不起作用
- database - NoSuchMethodError:在 Flutter 中使用 Dart 和 Firestore 调用了方法“get”
- python - OctoPrint API,发出 POST 请求时出现错误 400