Redux操作已调度,但状态未相应更新

cunj1qz1  于 2022-11-12  发布在  其他
关注(0)|答案(4)|浏览(163)

当我单击删除按钮时,将调度操作(removeBus)并发送正确的有效负载值,但存储区未更新,这是我的busSlice文件

import { createSlice } from "@reduxjs/toolkit";
const initialState = [
  {
    id: "0",
    description: "bus1"
  },
  {
    id: "1",
    description: "bus2"
  }
];
const busSlice = createSlice({
  name: "bus",
  initialState,
  reducers: {
    removeBus: (state, action) => {
      state.filter((bus) => bus.id !== action.payload);
      console.log(action.payload);
    }
  }
});
export const { removeBus } = busSlice.actions;
export default busSlice.reducer;

这里是我创建和导出存储的地方

import { configureStore } from "@reduxjs/toolkit";
import busReducer from "../features/busSlice";
export const store = configureStore({
  reducer: {
    busses: busReducer
  }
});

使用状态的组件在以下代码中创建,App Package 在redux提供程序组件中,上述存储作为props在index.js中提供

import "./styles.css";
import { useSelector, useDispatch } from "react-redux";
import { removeBus } from "./features/busSlice";
export default function App() {
  const dispatch = useDispatch();
  const busses = useSelector((state) => state.busses);
  const handleRemove = (id) => {
    dispatch(removeBus(id));
  };

  return (
    <div className="App">
      {busses.map((bus) => (
        <ul>
          <li key={bus.id}>
            <p>{bus.description}</p>
            <button onClick={() => handleRemove(bus.id)}>delete</button>
          </li>
        </ul>
      ))}
    </div>
  );
}

使用redux dev工具,我可以看到一个操作busses\removeBus被分派了适当的有效负载值,但是状态没有发生任何变化。

gcuhipw9

gcuhipw91#

您可以变更:

removeBus: (state, action) => {
      state.filter((bus) => bus.id != action.payload);
      console.log(action.payload);
    }

可以是bus.idaction.payload的数据类型不同。

9w11ddsr

9w11ddsr2#

您没有正确更新状态您需要说将我的状态更改为筛选状态
就像这样

removeBus(state, action){
      state = state.filter((bus) => bus.id !== action.payload);
      console.log(action.payload);
}
ff29svar

ff29svar3#

我也有这个问题。
在我的情况下,代码看起来像这样:

const someSlice = createSlice({
  name: 'test',
  initialState: null, 
  reducers: {
  addData(state, action) {
     state = action.payload
   }
 } 
});

这不起作用

const someSlice = createSlice({
  name: 'test',
  initialState: null, 
  reducers: {
  addData(state, action) {
     state = action.payload;
     return state;
   }
 } 
});

这起作用了。
但这很奇怪,不应该是这样的工作方式。

ej83mcc0

ej83mcc04#

您需要返回已更新的状态

import { createSlice } from "@reduxjs/toolkit";
const initialState = [
  {
    id: "0",
    description: "bus1"
  },
  {
    id: "1",
    description: "bus2"
  }
];
const busSlice = createSlice({
  name: "bus",
  initialState,
  reducers: {
    removeBus: (state, action) => {
      state = state.filter((bus) => bus.id !== action.payload);
      return state;
    }
  }
});
export const { removeBus } = busSlice.actions;
export default busSlice.reducer;

相关问题