【发布时间】:2020-10-24 20:05:48
【问题描述】:
我有一个由后端服务器管理的实体的 Redux 切片和 thunk 操作。我有 Redux thunk 实现的“创建”操作。当服务器收到带有实体详细信息的创建请求时,它会返回服务器生成的新 ID。如何在调用者组件中获取该 ID?
我的操作(使用 Redux Toolkit 编写):
export const createTodoAction = createAsyncThunk(
"todos/CREATE",
async (todo: Todo) => {
const fullTodo = await createTodoApi(todo);
return fullTodo; // Contains the ID from the server
}
);
我的组件:
function CreateTodoForm() {
const dispatch = useDispatch();
const onFormSubmit = (form: Todo) => {
dispatch(createTodoAction(form));
// How can I get the ID here?
}
...
}
我的直观解决方案是直接从组件调用 API 并将 createTodoAction 转换为常规 Redux 操作(而不是 thunk)。但是我所有的其他操作都是用 Redux thunk 编写的,所以一个操作必须直接从组件调用 API 似乎有点奇怪。
有没有办法从调用者组件中的 thunk 动作中获取响应?
【问题讨论】:
标签: reactjs redux redux-thunk