所以,我得到了这个函数 fetchData(),它返回一个被拒绝或已解决的 promise 。如果 promise 解决了我如何在页面上呈现它?
function Fetchdata() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve(`resolved`);
} else {
reject(new Error("err"));
}
}, time);
});
}
最佳答案
- 为每个请求状态提供一些初始状态
- 使用 promise-chain 或 async/wait with try/catch
- 更新渲染函数
使用 promise 链的力量。
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
}
}
关于javascript - 在 ReactJS 中呈现已解决或已拒绝的 Promise 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63717787/