使用@reduxjs/toolkit时无法更新redux中的状态



我目前开始学习redux。我的代码与core redux完美配合,然后我尝试了@reduxjs/toolkit,现在我无法访问该函数来更改存储中的状态。这是我的减速器代码。


const seasonEdits = createSlice({
name: "seasons",
initialState: [],
reducers: {
addSeason(state, action) {
state.push(action.payload);
console.log("this here");
},
removeSeason(state, action) {
state.filter((season) => season.id !== action.payload);
},
markComplete(state, action) {
state.map((season) => {
if (season.id == action.payload) season.isWatched = !season.isWatched;
});
},
},
});
export const { addSeason, removeSeason, markComplete } = seasonEdits.actions;
export default seasonEdits.reducer;

和我的store.js文件

import { configureStore } from "@reduxjs/toolkit";
import seasonReducer from "./reducer";
export default store = configureStore({
reducer: {
seasons: seasonReducer,
},
});

以及具有添加功能的add.js文件。调用handleSubmit函数,该函数正在创建一个对象并将其添加到作为存储中状态的数组中。

const handleSubmit = async () => {
try {
if (!name || !totalNoSeason) {
return alert("Please add both fields");
}
const seasonToAdd = {
id: shortid.generate(),
name,
totalNoSeason,
isWatched: false,
};
addSeason(seasonToAdd);
navigation.navigate("Home");
} catch (error) {
console.log(error);
}
};

const mapDispatchToProps = (dispatch) => {
return {
addSeason: (data) => dispatch(addSeason(data)),
};
};
Add.propTypes = {
addSeason: propTypes.func.isRequired,
};
export default connect(null, mapDispatchToProps)(Add);

问题是array.map()array.filter((返回新的数组!现在,你的减速器正在调用这些函数,然后丢弃新的数组:

removeSeason(state, action) {
// The return value is thrown away and ignored!      
state.filter((season) => season.id !== action.payload);
},

您需要返回新值:

removeSeason(state, action) {
// Now RTK will see the new return value      
return state.filter((season) => season.id !== action.payload);
},

请参阅https://redux-toolkit.js.org/usage/immer-reducers#resetting-以及替换状态以获取更多详细信息。

最新更新