8

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

我看到该动作已被调度,但就像切片减速器没有听它或其他东西一样。

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

4

1 回答 1

4

我认为您与createSliceAPI不匹配。

从您的代码中,您尝试为操作实现侦听器,因此您可能希望extraReducers改用:

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

注意API的reducersprop :createSlice

reducers: Object<string, ReducerFunction | ReducerAndPrepareObject>

如果你想使用sayreducers应该是:

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

@markeriksoncreateSlicereducers 字段用于定义reducers 并生成与这些reducers 匹配的操作。该extraReducers字段用于处理已在别处定义的操作。

于 2020-06-07T14:04:31.773 回答