【问题标题】:How to return redux state from async function?如何从异步函数返回 redux 状态?
【发布时间】:2020-07-02 06:59:23
【问题描述】:

我的减速器无法返回正确的状态。从我的其他组件访问天气时,我得到了一个承诺。我在 getWeather 函数中使用了 async await,但我不确定为什么我仍然从返回值中得到一个 Promise。

const initState = {
    date: new Date(),
    weather: "",
};

const getWeather = async (difference) => {
    await fetch(
        "https://api.openweathermap.org/data/2.5/onecall?lat=1.290270&lon=103.851959&%20exclude=hourly,daily&appid=" +
            WEATHER_API_KEY
    )
        .then((response) => response.json())
        .then((data) => {
            return data["daily"][difference]["weather"][0]["main"];
        });
};

export default function (state = initState, action) {
    switch (action.type) {
        case DATE_SELECT:
            const day_difference =
                moment(action.payload).date() - moment(state.date).date();
            return {
                date: action.payload,
                weather: getWeather(day_difference),
            };

        default:
            return state;
    }
}

【问题讨论】:

    标签: reactjs redux async-await


    【解决方案1】:

    Redux 默认不支持异步操作。您将需要一个诸如redux-thunk 之类的中间件来支持它。

    基本上,您将需要一个函数来获取天气数据,以便在数据解析后调度另一个操作,例如:

    // Get weather need to be a function that return an action    
    const getWeather = (difference) => {
            return (dispatch) => fetch(
                "https://api.openweathermap.org/data/2.5/onecall?lat=1.290270&lon=103.851959&%20exclude=hourly,daily&appid=" +
                    WEATHER_API_KEY
            )
                .then((response) => response.json())
                .then((data) => {
                    // Dispatch a function with the weather data
                    dispatch("RECEIVE_WEATHER", data["daily"][difference]["weather"][0]["main"]);
                });
        };
    

    有关该主题的示例可以在 redux 文档网站上找到:https://redux.js.org/advanced/async-actions

    【讨论】:

      【解决方案2】:

      async function 总是返回一个承诺。 Read here

      因此,要处理您的情况,您必须使用一些中间件来处理副作用,例如 Redux thunkredux-saga

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 2020-12-10
        • 2020-07-29
        • 2023-03-08
        • 2019-08-06
        • 2021-03-04
        • 2020-12-08
        相关资源
        最近更新 更多