【问题标题】:Redux thunk caller get responseRedux thunk 调用者得到响应
【发布时间】: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


    【解决方案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
          }
       }
    
       ...
    }
    

    【讨论】:

    • 嗯...有趣,我在文档中看到了,但它从来没有为我工作过...似乎dispatch返回function而不是promise(至少Typescript 中的类型定义)。我不能在dispatch 上使用awaitthen...
    • 您需要正确输入您的dispatchredux-toolkit.js.org/usage/…
    • 我的打字有问题。从createSlice 生成的reducer 使用AnyAction 定义,因此store.dispatch 的类型为Dispatch<AnyAction>。所以它不接受thunk。类似于:github.com/DefinitelyTyped/DefinitelyTyped/issues/45575
    • 是的,如链接的文档页面所示,您需要明确声明您使用的是接受 thunk 的 Dispatch 版本。
    • @markerikson,真的。但是export type AppDispatch = typeof store.dispatch 实际上是type AppDispatch = Dispatch<AnyAction>,它不接受thunk。我的切片仅使用 extraReducers 和 thunks 处理程序。我应该如何用接受 thunk 的Dispatch 声明AppDispatch?我错过了什么?...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2017-10-04
    • 2017-05-28
    • 2016-06-12
    • 2017-10-08
    • 1970-01-01
    • 2020-08-18
    相关资源
    最近更新 更多