【发布时间】:2019-11-15 09:55:46
【问题描述】:
我正在从 Redux Saga 进行登录身份验证调用,因此在 JSX 中我可以使用条件渲染等待状态更新,但我该如何等待它进入 ex。 onSubmit 功能,以便我可以在登录成功时重定向。
我正在使用条件语句来检查用户是否在发送 props.login(values) 后立即在 onSubmit 函数中登录,但我得到了将 isLoggedIn 设置为 false 的旧状态。
登录组件
<Formik
initialValues={{
email: '',
password: '',
}}
validationSchema={LoginSchema}
onSubmit={(
values,
{ setSubmitting, resetForm },
) => {
props.login(values);
setTimeout(() => {
if(props.isLoggedIn) {
props.history.push('/'); // Functional Component
} else {
resetForm();
}
setSubmitting(false);
}, 500);
}}
>
初始状态
const initialState = {
currentUser: {},
isLoggedIn: false,
errors: '',
propertyMessages: '',
};
减速器
const rootReducer = (state = initialState, action) => {
switch (action.type) {
case AUTH: {
if (action.payload.error) {
return {
...state,
errors: action.payload.error,
};
} else {
localStorage.setItem('access-token', action.payload);
const user = jwtDecode(action.payload);
return {
...state,
errors: '',
isLoggedIn: true,
currentUser: {
id: user.id,
name: user.name,
},
};
}
}
case LOGOUT: {
localStorage.removeItem('access-token');
return {
...state,
isLoggedIn: false,
currentUser: {},
errors: '',
};
}
default:
return state;
}
};
Redux 传奇
function* loginSaga(payload) {
try {
const data = yield call(loginCall, payload); // Get token
yield put({ type: AUTH, payload: data });
} catch (e) {
console.log(e);
}
}
isLoggedIn 在props.login(values) 调度之后立即设置为true,但因为如果使用旧状态调用get,重定向逻辑就在调度程序之后。
如果重定向逻辑可以延迟或在条件渲染的情况下组件渲染并导致重定向,则会发生预期的结果,因为它将具有更新的值。
【问题讨论】:
标签: reactjs express authentication redux redux-saga