我有一个useSelector,它会向我返回存储在全局状态中的值,我也有一个异步操作,方法是使用react redux thunk,它内部会改变状态值,但是,当我调用thunk函数并在完成后,useSelector值似乎无法立即更新,会稍有延迟...执行thunk函数后如何从状态中获取最新值?
// thunk
function savePageData() {
return async(dispatch, getState) => {
await fetch(...).then(res => dispatch(LOAD_DATA, res));
dispatch(somethingelse);
}
}
// main
const myPage = () => {
const user = useSelector(state => return state.user);
const dispatch = useDispatch();
const onClick = async() => {
await dispatch(savePageData());
if (user.active). // here the user after above dispatch is still the old state
{ ... }
}
}
它将以这种方式工作
const onClick = async() => {
return (_dispatch, getState) => {
await dispatch(savePageData());
if (getState().user.active). // now user is latest, but is this a correct way and why?
{ ... }
}
}
或这种方式
const onClick = async() => {
await dispatch(savePageData()).then(
if (user.active). // now user is latest, but is this a correct way and why?
{ ... }
);
}