【发布时间】:2022-12-10 11:26:18
【问题描述】:
我正在尝试创建一个对象并将其添加到 reducer,但让 action/reducer 负责生成 id。
根据这个answer,似乎接受的模式是在动作创建者中生成 id:
const todosSlice = createSlice({
name: "todos",
initialState: [],
reducers: {
addTodo: {
reducer(state, action) {
state.push(action.payload);
},
prepare(text) {
const id = uuid();
return { payload: {text, id} };
}
}
}
})
但是,假设我想在创建待办事项后使用/引用 id,比如
dispatch(addTodo('Say hello world')) // creates a todo with a uuid
...
id = <some way to get the id>
doSomethingElseWithTodoGivenId()
Redux-Toolkit 是否为实现这一目标提供任何帮助?我查看了createAsyncThunk,但它似乎更关注异步数据获取状态。
我知道我可以用 redux-thunk 做到这一点(通过等待调度并让 thunk 操作生成 id):
const id = await dispatch(createTodoWithGeneratedId('Say hello world'))
或者让调用者生成 id。但我想知道是否有更好的方法。
【问题讨论】:
标签: reactjs redux redux-toolkit