代码之家  ›  专栏  ›  技术社区  ›  nrofis

Redux thunk调用者获取响应

  •  1
  • nrofis  · 技术社区  · 4 年前

    我的操作(使用Redux工具箱编写):

    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操作获得响应?

    1 回复  |  直到 4 年前
        1
  •  1
  •   nrofis    4 年前

    createAsyncThunk 返回作为结果的最终已调度操作 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
          }
       }
    
       ...
    }