【问题标题】:How to return async data in reducer如何在reducer中返回异步数据
【发布时间】:2021-01-07 02:59:12
【问题描述】:

我从应用程序的后端获取了一些数据,但我很难正确返回状态。 代码:

if (action.type === actionTypes.getList) {
    const id = action.payload.userId;
    
    Axios.post(`${apiUrl}/lists`, {
        userId: id,
    })
        .then((response) => {
            const newLists = response.data;
            return { ...listState, lists: newLists };
        })
        .catch((e) => {
            console.log("There has been error: ", e);
        });
}

在这个状态下,reducer 状态是未定义的,我得到它是因为我没有从主 If 语句返回任何内容。

if (action.type === actionTypes.getList) {
    const id = action.payload.userId;

    const newLists = Axios.post(`${apiUrl}/lists`, {
        userId: id,
    })
        .then((response) => {
            const res = response.data;
            return res
        })
        .catch((e) => {
            console.log("There has been error: ", e);
        });
    return { ...listState, lists: newLists };
}

这里我的减速器状态是空对象,我在控制台中得到 Promise { : "pending" }。在异步函数完成后,有什么方法可以调用主返回语句吗?或者有什么其他方法可以解决这个问题?

【问题讨论】:

  • 您不能等待同步函数中的异步结果。因此,您也应该使周围的函数异步,并在您的第一个 sn-p 中返回或等待您从 Axios.post() 获得的 Promise。
  • 当数据异步到达时需要dispatch一个新事件
  • 是的,我做到了,谢谢你的建议!

标签: javascript reactjs asynchronous async-await reducers


【解决方案1】:

我建议你对 reducer 和 dispatch 函数之间的任何中间件逻辑使用 Redux 操作。 见https://redux.js.org/tutorials/fundamentals/part-3-state-actions-reducers 我不确定你的代码有什么问题...

【讨论】:

    【解决方案2】:

    好的,所以我想通了...我还必须在上下文中重新编写我的代码:

    listContext.js:

    useEffect(() => {
        if (userId) {
            Axios.post(`${apiUrl}/lists`, {
                userId: userId,
            }).then((response) => {
                const lists = response.data;
                dispatch({ type: actionTypes.getListData, payload: { lists: lists } });
            });
        }
    }, [userId]);
    

    listReducer.js:

    if (action.type === actionTypes.getListData) {
        const { lists } = action.payload;
        console.log(lists);
    
        return { ...listState, lists: lists };
    }
    

    基本上是在上下文中获取数据,在数据到达后调用 dispatch 并从 reducer 返回新状态。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-08
      • 2020-08-08
      • 1970-01-01
      • 2021-12-14
      • 2019-08-25
      • 1970-01-01
      相关资源
      最近更新 更多