react redux工具箱中的还原器未更新状态



我的减速器removeMovie不工作。每次我从没有一个元素的状态获取所有初始数据时。我需要在每次通话中更新状态。

import { createSlice } from '@reduxjs/toolkit';
import movies from '../../services/movies.json';
export const movieSlice = createSlice({
name: 'movie',
initialState: movies,
reducers: {
addMovie: (state, action) => {
state.push(action.payload);
},
removeMovie: (state, action) => {
state = state.filter(movie => movie.title !== action.payload);
console.log(JSON.stringify(state));
},
},
});
// Action creators are generated for each case reducer function
export const { addMovie, removeMovie } = movieSlice.actions;
export default movieSlice.reducer;

Immer库不会跟踪您在removeMoviie reducer中所做的操作。通过这行state = state.filter(movie => movie.title !== action.payload);,您正在分配局部状态变量,而这实际上并不是状态的改变。你可以试试这个:

removeMovie: (state, action) => {
const newState = state.filter(movie => movie.title !== action.payload);
console.log(JSON.stringify(newState));
return newState;
},

你可以在以下链接上找到更多关于这方面的信息:immer使用模式

相关内容

  • 没有找到相关文章

最新更新