在reduceer中未触发redux-toolkit操作

时间:2020-06-07 13:57:46

标签: javascript reactjs redux redux-toolkit

我正在尝试使用@ 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

1 个答案:

答案 0 :(得分:4)

我认为您不匹配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));

Edit redux-toolkit

@markerikson:在createSlice中,化简器字段用于定义化简器并生成与那些化简器匹配的动作。 extraReducers字段用于处理在其他位置已定义的操作。