Hook useReducer发送2次

问题描述 投票:1回答:1

我有一个“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;
}}

和我的Provider Context使用useReducer Hook。如果客户端已记录,则useEffect Hook用于调度操作“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”(dispatch)。我需要将状态传递给其他子组件,但不需要传递inicial值(“false”)。

我有一个仪表板组件(仅用于用户登录),在我使用此组件的效果我需要这样做:

if(!context.stateUser.isAuthenticated) {
        props.history.push('/login');

}

在我的登录中:

if(context.stateUser.isAuthenticated) {
        props.history.push('/');
}

这有效。如果我已登录并转到“/”即可,如果我转到“/ login”,则会重定向到“/”。

但问题是在dispatch和useReducer中重新渲染。状态是:false-> true,然后它会导致这种效果:输入“/” - >“/ login(false)” - >“/(true)”

我该如何防止这种影响? / - > / login - > / == enter-> false-> true。我需要:输入 - >真

javascript reactjs login hook
1个回答
0
投票

我的建议是将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));
},[])
© www.soinside.com 2019 - 2024. All rights reserved.