【问题标题】:How to update in correct mode array using Promise function in React.useState?如何使用 React.useState 中的 Promise 函数以正确的模式数组更新?
【发布时间】:2021-04-07 05:36:53
【问题描述】:

如果 React.useState 包含数组,如何使用 Promise 函数更新 State。 我写了我尝试做的简化示例

  function md5(file: any, base64?: boolean): Promise<unknown> {
    // return new Promise((resolve, reject) => { ...
    return null;
  };
  const [state, setState] = useState(
    [...Array(10).keys()].map(el => {
      return { name: `name${el}`, file: `file${el}`, hash: "" };
    })
  );
  state.forEach(el => {
    md5(el.file).then((hash: string) => {
      const newState = [
        ...state,
        {
          name: el.name,
          file: el.file,
          hash,
        },
      ];
      // console.log(state); == always not uptated
      setState(newState);
    });
  });

如果我尝试使用 map 作为数组函数返回的不是哈希而是 Promise

【问题讨论】:

    标签: arrays reactjs typescript use-state


    【解决方案1】:

    我会使用Promise.all 等待所有md5 调用完成:

    Promise.all(state.map(el => md5(el.file).then(hash => [hash, el])))
      .then((results) => {
        const newState = [
          ...state,
          ...results.map(([hash, el]) => ({ name: el.name, file: el.file, hash }))
        ];
        setState(newState);
      })
        .catch(handleErrors); // don't foget to catch errors
    

    另一种选择是在setState 中使用回调,这样之前完成的md5 调用就不会被覆盖。

    const newValue = { name: el.name, file: el.file, hash };
    setState(state => [...state, newValue]);
    

    【讨论】:

    • 非常感谢。第二种方式适合我,因为在每次更改时我都会异步进行另一个操作
    猜你喜欢
    • 2016-08-26
    • 2021-05-10
    • 2018-01-10
    • 1970-01-01
    • 2020-05-23
    • 2020-06-10
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    相关资源
    最近更新 更多