使用React和Redux制作简单的天气应用程序时遇到麻烦。
我有两个减速器。一种是将数据添加到数组中,另一种是使用find方法从数组中删除数据。
这是代码:
// actions
// fetching weather api
export const fetchWeather = term => {
return async dispatch => {
const res = await api.get(
`/data/2.5/weather?q=${term}&APPID=132123123132`
);
dispatch({ type: "FETCH_WEATHER", payload: res.data });
};
};
// delete a list that matches the selected id
export const listDelete = id => {
return {
type: "LIST_DELETE",
paylod: id
};
};
// reducers
// reducer that put a new data into an array
const reducerIndex = (state = [], action) => {
switch (action.type) {
case "FETCH_WEATHER":
return [...state, action.payload];
default:
return state;
}
};
// reducer that deleting the data that id selected
const reducerIndexDel = (state = [], action) => {
switch (action.type) {
case "LIST_DELETE":
return state.find(city => city.id !== action.payload);
default:
return state;
}
};
export default combineReducers({
reducerIndex,
reducerIndexDel
});
您可能知道,浏览器给我一个错误,提示“给定操作“ LIST_DELETE”,减速器“ reducerIndexDel”返回未定义。”
我能够获取想要的数据,但是如何使reducerIndexDel能够识别以前的状态?
答案 0 :(得分:1)
只需使用filter
即可获取不包含具有ID的城市的州。
return state.filter(city => city.id !== action.payload)
答案 1 :(得分:1)
我认为您在listDelete
函数中对“有效载荷”的拼写错误。
您正在尝试访问action.payload
,但实际上它被写为paylod
。