gpt4 book ai didi

javascript - 在 reducer 中未触发 redux-toolkit 操作

转载 作者:行者123 更新时间:2023-12-03 07:06:17 24 4
gpt4 key购买 nike

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

我看到该 Action 已调度,但就像切片 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 createSlice 的 Prop 接口(interface):
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));
Edit 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.

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com