我正在尝试使用 @reduxjs/Toolkit 触发一个简单的操作,但它不起作用。

我看到该 Action 已被分派(dispatch),但就像切片 reducer 没有在听它或其他什么一样。

const say = createAction("ui/say", what => ({ payload: what }));

const uiSlice = createSlice({
  name: "ui",
  initialState: { said: "" },
  reducers: {
    [say.type]: (state, action) => {
      console.log("saying", action.payload); //<-- not showing, why?
      state.currentList = action.payload;
    }
  }
});

const store = configureStore({
  reducer: combineReducers({
    ui: uiSlice.reducer
  })
});

const Chat = () => {
  const dispatch = useDispatch();
  const [whatToSay, setWhatToSay] = useState("");
  const whatWasSaid = useSelector(state => state.ui.said);

  const onSubmit = e => {
    e.preventDefault();
    dispatch(say(whatToSay));
    setWhatToSay("");
  };

  return (
    <div>
      <form onSubmit={onSubmit}>
        <input type="text" onChange={e => setWhatToSay(e.target.value)} />
        <button>Say</button>
      </form>
      {whatWasSaid ? <p>You said: {whatWasSaid}</p> : <p>Say something</p>}
    </div>
  );
};

这是一个最小的复制示例:
https://codesandbox.io/s/redux-toolkit-0tzxs?file=/src/index.js

最佳答案

我认为您与 createSlice API 不匹配。
从您的代码中,您尝试为某个操作实现一个监听器,因此您可能希望改用 extraReducers:

const uiSlice = createSlice({
  name: "ui",
  initialState: { said: "" },
  // Not reducers: {}
  extraReducers: {
    [say.type]: (state, action) => {
      console.log("saying", action.payload);
      state.currentList = action.payload;
    }
  }
});
注意 reducers API 的 createSlice 属性:
reducers: Object<string, ReducerFunction | ReducerAndPrepareObject>
如果你想在 say 中使用 reducers 它应该是:
const say = (state, payload) => {
  console.log("saying", payload);
  state.currentList = payload;
};


const uiSlice = createSlice({
  name: "ui",
  initialState: { said: "" },
  reducers: { say }
});

// Usage
dispatch(uiSlice.actions.say(whatToSay));
javascript -  reducer 中未触发 redux-toolkit 操作-LMLPHP

关于javascript - reducer 中未触发 redux-toolkit 操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62246412/

10-10 07:56