Redux重拨呼叫者获得响应

时间:2020-10-24 20:05:48

标签: reactjs redux redux-thunk

我有一个由后端服务器管理的实体的Redux slice和thunk操作。我有Redux thunk实现的“创建”操作。当服务器收到带有实体详细信息的Create请求时,它将返回服务器生成的新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有点奇怪。

有什么方法可以从调用者组件中的重击操作中获得响应吗?

1 个答案:

答案 0 :(得分:1)

使用createAsyncThunk创建的thunk返回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
      }
   }

   ...
}