【问题标题】:Progress bar with Redux createAsyncThunk?Redux createAsyncThunk 的进度条?
【发布时间】:2021-01-22 13:32:01
【问题描述】:

我正在用 React + Redux 编写一个简单的程序。 在createAsyncThunk 内部,我需要发送多个请求来发送数据块。 现在我的代码如下所示;

export const sendData = createAsyncThunk<
  void,
  {
    id: string;
    data: Uint8Array;
  }
>("files/upload", async (props) => {
  const { uploadId } = await api.init();
  try {
    let i = 0;
    while (props.data.length > i * CHUNK_SIZE) {
      const chunkedData ... // Here I create chunked data from props.data.
      await api.uploadFileChunk({
        uploadId: uploadId,
        data: chunkedData,
      });
      i++;
    }
    await api.complete({
      id: props.id,
      uploadId: uploadId,
    });
  } catch (err) {
    await api.abort({ uploadId: uploadId });
  }
});

目前,我在发送数据时显示了一个加载栏,但它没有告诉进度。我想改进程序以显示进度条,因为如果要发送的数据很大,则需要很长时间。 如何使用createAsyncThunk 管理progress

【问题讨论】:

    标签: redux react-redux redux-toolkit


    【解决方案1】:

    每次加载块时,您都需要调度某种操作。这样,您的商店就会知道已加载了多少,并可以选择进度。 createAsyncThunk 函数旨在为pendingfulfilledrejected 创建三个动作创建者。

    props 之后有一个second argument,您可以在回调中访问它。那就是包含您商店的dispatch 方法的thunkAPI 对象。您应该可以在主 payloadCreator 回调中使用此 dispatch 附加操作。

    注意这里的catch-ing 错误。我不确定,但我认为这会导致fulfilled 响应,因此您需要使用rejectWithValue

    它应该看起来像这样(显然未经测试)

    
    export const sendData = createAsyncThunk<
    void,
    {
      id: string;
      data: Uint8Array;
    }
    >(
      "files/upload", 
      async (props, {dispatch, rejectWithValue}) => {
      const { uploadId } = await api.init();
      try {
        let i = 0;
        while (props.data.length > i * CHUNK_SIZE) {
          const chunkedData = // Here I create chunked data from props.data.
          await api.uploadFileChunk({
            uploadId: uploadId,
            data: chunkedData,
          });
          i++;
          dispatch({
            type: "files/uploadProgress",
            percent: //calculate this
          });
        }
        await api.complete({
          id: props.id,
          uploadId: uploadId,
        });
      } catch (err) {
        await api.abort({ uploadId: uploadId });
        rejectWithValue(err);
      }
    });
    

    如果我正确阅读了您的循环,我认为您需要i += CHUNK_SIZE 而不是i++,因为您一次上传一堆。我将由您来计算进度计算。

    【讨论】:

      猜你喜欢
      • 2021-08-23
      • 2021-04-29
      • 2021-11-11
      • 2020-09-26
      • 1970-01-01
      • 2021-09-01
      • 2021-09-17
      • 2021-08-29
      • 1970-01-01
      相关资源
      最近更新 更多