【问题标题】:Render resolved or rejected value of Promise in ReactJS在 ReactJS 中呈现已解决或拒绝的 Promise 值
【发布时间】:2020-12-22 08:18:42
【问题描述】:

所以,我有这个函数 fetchData(),它返回一个被拒绝或解决的承诺。如果 promise 解决了我如何在页面上呈现它?

function Fetchdata() {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (Math.random() > 0.5) {
                resolve(`resolved`);
            } else {
                reject(new Error("err"));
            }
        }, time);
    });
}

【问题讨论】:

    标签: javascript reactjs typescript react-native es6-promise


    【解决方案1】:
    • 为每个请求状态提供一些初始状态
    • 将 promise-chain 或 async/wait 与 try/catch 结合使用
    • 更新渲染函数

    利用承诺链的力量。

    class App extends React.Component {
       state = {
         data: null,
         error: null,
         loading: true;
       };
    
       componentDidMount() {
          fetchData()
            .then(data => {
              // promise resolved
              // handle happy path, update state.data
            })
            .catch(err => {
              // promise rejected
              // handle sad path, update state.error
            })
            .finally(() => {
              // promise is settled
              // set loading false
            });
       }
         
       render() {
          const { data, error, loading } = this.state;
    
          if (loading) {
            <div>Loading...<.div>;
          }
    
          return (
              <div>
                  <h1></h1>
                  {error && <div>Error</div>}
                  {data && <div>{data}</div>
              </div>
          );
      }
    }
    

    以类似的方式在 try/catch/finally 中使用 async/await

    async componentDidMount() {
      try {
        const data = await fetchData();
        // promise resolved
        // handle happy path, update state.data
      } catch(err) {
        // promise rejected
        // handle sad path, update state.error
      } finally {
        // promise is settled
        // set loading false
      }
    }
    

    【讨论】:

    • 很好的答案,我只是有一个澄清问题,finally 块中的update loading state 只是为了避免代码重复,对吧?
    • @nabais 谢谢。正确,另一种方法是在两个逻辑分支中将加载状态设置为 false。
    猜你喜欢
    • 2017-03-14
    • 1970-01-01
    • 2020-09-17
    • 2020-09-12
    • 2019-04-17
    • 2023-03-17
    • 2020-04-15
    • 2015-01-25
    • 1970-01-01
    相关资源
    最近更新 更多