首页 > 解决方案 > 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 开发工具中,它显示了状态变化。

在此处输入图像描述

标签: javascriptreactjsredux

解决方案


推荐阅读