Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 执行react redux thunk后,useSelector值未立即更改_Reactjs_Async Await_React Hooks_Redux Thunk - Fatal编程技术网

Reactjs 执行react redux thunk后,useSelector值未立即更改

Reactjs 执行react redux thunk后,useSelector值未立即更改,reactjs,async-await,react-hooks,redux-thunk,Reactjs,Async Await,React Hooks,Redux Thunk,我有一个useSelector,它将返回存储在全局状态中的值,我还有一个异步操作,通过使用react-redux thunk,它将更改状态值,但是,当我调用thunk函数并在它完成后,useSelector值似乎不会立即更新,它会有一点延迟…在执行thunk函数后,如何从状态获取最新的值 // thunk function savePageData() { return async(dispatch, getState) => { await fetch(...).then(r

我有一个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?
         { ... }
      );
   }