Redux thunk 调用者得到响应
Redux thunk caller get response
我有一个由后端服务器管理的实体的 Redux slice 和 thunk 操作。我有 Redux thunk 实施的“创建”操作。当服务器收到带有实体详细信息的创建请求时,它 returns 服务器生成的新 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 操作获得响应吗?
使用 createAsyncThunk
return 创建的 Thunks 作为 dispatch(thunk())
的结果的最终分派操作。所以,你可以 unwrap the result action to get the payload value:
function CreateTodoForm() {
const dispatch = useDispatch();
const onFormSubmit = async (form: Todo) => {
const resultAction = await dispatch(createTodoAction(form));
try {
const payload = unwrapResult(resultAction);
// do something with payload here
} catch (err) {
// call must have failed - can optionally handle error here
}
}
...
}
我有一个由后端服务器管理的实体的 Redux slice 和 thunk 操作。我有 Redux thunk 实施的“创建”操作。当服务器收到带有实体详细信息的创建请求时,它 returns 服务器生成的新 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 操作获得响应吗?
使用 createAsyncThunk
return 创建的 Thunks 作为 dispatch(thunk())
的结果的最终分派操作。所以,你可以 unwrap the result action to get the payload value:
function CreateTodoForm() {
const dispatch = useDispatch();
const onFormSubmit = async (form: Todo) => {
const resultAction = await dispatch(createTodoAction(form));
try {
const payload = unwrapResult(resultAction);
// do something with payload here
} catch (err) {
// call must have failed - can optionally handle error here
}
}
...
}