reactjs - 如何从异步函数返回 redux 状态?
问题描述
我的减速器无法返回正确的状态。从我的其他组件访问天气时,我得到了一个承诺。我在 getWeather 函数中使用了异步等待,但我不确定为什么我仍然从返回值中得到一个承诺。
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;
}
}
解决方案
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