简体   繁体   中英

redux-toolkit action not triggered in reducer

I'm trying to trigger a simple action using @reduxjs/Toolkit but it's not working.

I see that the action is dispatched but it's like the slice reducer is not listening to it or something.

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>
  );
};

Here's a minimal reproducing example:https://codesandbox.io/s/redux-toolkit-0tzxs?file=/src/index.js

I think you mismatched the createSlice API .

From your code, you trying to implement a listener for an action, so you might want to use extraReducers instead:

const uiSlice = createSlice({
  name: "ui",
  initialState: { said: "" },
  // Not reducers: {}
  extraReducers: {
    [say.type]: (state, action) => {
      console.log("saying", action.payload);
      state.currentList = action.payload;
    }
  }
});

Note the reducers prop of createSlice API:

reducers: Object<string, ReducerFunction | ReducerAndPrepareObject>

If you want to use say in reducers it should be:

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));

编辑 redux-toolkit

@markerikson : with createSlice , the reducers field is for defining reducers and generating actions that will match those reducers. The extraReducers field is for handling actions that were already defined elsewhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM