使用redux和redux thunk链接多个异步调度

时间:2020-05-03 15:02:25

标签: reactjs redux redux-thunk

在我的react组件中,我想调度一些异步动作。我有这样的东西

// action creator
const fetchUserContext = response => ({
  type: ActionType.FETCH_USRE,
  payload: response,
});

// in component
useEffect(() => {
  async function fetchData () {
    const userContext = await dispatch(fetchUserContext());
    const shoppingInfo = await dispatch(fetchShoppingInfo(userContext.user_id));
  }

  fetchData();
}, []);

这可行,但是我认为从redux存储中获取userContext信息比直接从动作创建者那里获取更有意义。我正在尝试类似以下的方法,但是它不起作用。

// in component

import { useSelector } from 'react-redux'

const userContext = useSelector(state => state.userContext);

useEffect(() => {
  async function fetchData () {
    await dispatch(fetchUserContext());
    // it doesn't work since userContext is still undefined
    const shoppingInfo = await dispatch(fetchShoppingInfo(userContext.user_id));
  }

  fetchData();
}, []);

我不知道什么是最好/正确的方法。感谢您提前提供的所有帮助。

0 个答案:

没有答案