我有一个authentication.reducer.js,它有:
export default function(state = initialState, action ){
switch(action.type) {
case SET_CURRENT_USER:
return {
...state,
isAuthenticated: !isEmpty(action.payload),
user: action.payload
}
default:
return state;
}}以及我的提供者与useReducer挂钩的上下文。和一个useEffect钩子,用于分派一个操作"setCurrentUser“,并在客户机被记录时将"isAuthenticated”设置为true。
import authReducer from "./reducers/authentication.reducer";
...
const [stateUser, dispatch] = useReducer(authReducer, {
isAuthenticated: false,
user: {}
});
useEffect(()=>{
if (localStorage.jwt) {
const decoded = localStorage.jwt;
dispatch(setCurrentUser(decoded));
}
},[])我在组件中放置了一个console.log(stateUser.isAuthenticated),这显示了"false“(初始值),然后显示了"true”(分派)。
我需要将状态(stateUser.isAuthenticated)传递给其他子组件,但不需要传递初始值("false")。
我有一个仪表板组件(仅供登录的用户使用),在这个组件的useEffect中,我需要这样做:
if(!context.stateUser.isAuthenticated) {
props.history.push('/login');
}在我的登录中:
if(context.stateUser.isAuthenticated) {
props.history.push('/');
}这个很管用。如果我登录并转到"/“是可以的,如果我转到"/login",这个重定向到"/”。
但问题是调度和useReducer中的重呈现。状态为: false->true,然后它会导致这样的效果:输入"/"->"/login“(false)"->"/ (真)”
如何防止这种影响?/ -> /login -> / == enter->false->true。我需要:输入-> true
发布于 2019-03-20 20:21:43
我的建议是将isAuthenticated设置为null以启动,并且只有在状态显式设置为true或false时才调用历史函数,如下所示:
if (context.stateUser.isAuthenticated === false) {
props.history.push('/login');
}
if (context.stateUser.isAuthenticated === true) {
props.history.push('/');
}确保使用三倍等于使比较严格比较。
这个有用吗?
编辑
如果要这样做,即使没有用户登录,也需要调用setCurrentUser。
useEffect(()=>{
const decoded = localStorage.jwt ? localStorage.jwt : "";
dispatch(setCurrentUser(decoded));
},[])https://stackoverflow.com/questions/55269424
复制相似问题