gpt4 book ai didi

reactjs - 页面刷新后 React useReducer Hook 状态丢失

转载 作者:行者123 更新时间:2023-12-05 06:21:35 28 4
gpt4 key购买 nike

当用户成功登录时,它会将身份验证状态从 null 更改为 true,并且在我刷新它设置的页面时登陆主页后来自 initialState(AuthState.js) 的默认状态值我想在用户刷新页面后保持状态。我正在使用 hooks reducer

登录.js

      import React, { useState, useContext, useEffect } from "react";
import AlertContext from "../../context/alert/alertContext";
import AuthContext from "../../context/auth/authContext";
const Login = props => {
const authContext = useContext(AuthContext);
const { login, isAuthenticated,loading } = authContext;
useEffect(() => {
if (isAuthenticated) {
props.history.push("/");
}
if (error === "Invalid Credentials") {
setAlert(error, "danger");
clearErrors();
}
// eslint-disable-next-line
}, [error, isAuthenticated, props.history]);
const [user, setUser] = useState({
email: "",
password: ""
});
const { email, password } = user;
const onChange = e => setUser({ ...user, [e.target.name]:
e.target.value });
const onSubmit = e => {
e.preventDefault();
if (email === "" || password === "") {
setAlert("Please fill in all fields", "danger");
removeLoading();
} else {
login({
email,
password
});
}
};
return (
<div className="form-container">
<form onSubmit={onSubmit}>
<div className="form-group">
<label htmlFor="email">Email Address</label>
<input type="email" name="email" value={email} onChange={onChange}
/>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
value={password}
onChange={onChange}

/>
</div>
<input
type="submit"
value="Login"
className="btn btn-primary btn-block"
/>
</form>
</div>
);
};
export default Login;

AuthState.js

这是初始状态代码

 const AuthState = props => {

const initialState = {
//token: localStorage.getItem("token"),
isAuthenticated: null,
loading: false,
user: null,
error: null

};


const [state, dispatch] = useReducer(authReducer, initialState);
// Load User
const loadUser = async () => {
if (localStorage.token) {
console.log(localStorage.token)
setAuthToken(localStorage.token);
}

try {

const res = await axios.get("/api/auth");

dispatch({ type: USER_LOADED, payload: res.data });
} catch (err) {

dispatch({ type: AUTH_ERROR });
}
};

// Login User
const login = async formData => {
const config = {
headers: {
"Content-Type": "application/json"
}
};

try {
const res = await axios.post("api/auth", formData, config);
//console.log(res.data)
dispatch({
type: LOGIN_SUCCESS,
payload: res.data
});

loadUser();
} catch (err) {
dispatch({
type: LOGIN_FAIL,
payload: err.response.data.msg
});
}
};
return (
<AuthContext.Provider
value={{

isAuthenticated: state.isAuthenticated,
loading: state.loading,

user: state.user,
error: state.error,
login,
logout

}}
>
{props.children}
</AuthContext.Provider>
);
};

导出默认的AuthState;

authReducer.js这是 reducer 钩子(Hook)代码 导入 {

  REGISTER_FAIL,
USER_LOADED,
AUTH_ERROR,
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGOUT,
CLEAR_ERRORS,
} from "../types";

export default (state, action) => {
switch (action.type) {


case USER_LOADED:

return {
...state,
isAuthenticated: true,
loading: false,
user: action.payload
};
case LOGIN_SUCCESS:

localStorage.setItem("token", action.payload.token);
return {
...state,
...action.payload,
isAuthenticated: true,
loading: false
};

case AUTH_ERROR:
case LOGIN_FAIL:

localStorage.removeItem("token");

return {
...state,
token: null,
isAuthenticated: false,
loading: false,
user: null,
error: action.payload
};

case REMOVE_LOADING:
return {
...state,
loading: false
};
default:

return state;
}
};

私有(private)路线

import React, { useContext } from "react";
import { Route, Redirect } from "react-router-dom";
import AuthContext from "../../context/auth/authContext";

const PrivateRoute = ({ component: Component, ...rest }) => {
const authContext = useContext(AuthContext);
const { isAuthenticated } = authContext;

return (

<Route
{...rest}
render={props =>
!isAuthenticated ? (
<Redirect to="/login" />
) : (
<Component {...props} />
)
}
/>
);
};

export default PrivateRoute;

主页

import React, { useContext, useEffect } from "react";
import AuthContext from "../../context/auth/authContext";

const Home = () => {
const authContext = useContext(AuthContext);

useEffect(() => {
//authContext.setLoading(true);
authContext.loadUser();

// eslint-disable-next-line
}, []);
return (
<div className="grid-2">
<div>
<ContactForm />
</div>
<div>
<ContactFilter />
<Contacts />
</div>
</div>
);
};

export default Home;

最佳答案

您可以将您的登录状态传递给 reducer 并更新您的初始状态。或使用 localStorage 之类的

   let initialState={
loggedIn: localStorage.getItem('isLoggedin' ) || false;
}

关于reactjs - 页面刷新后 React useReducer Hook 状态丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59730267/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com