[英]Render resolved or rejected value of Promise in ReactJS
So, I've got this function fetchData() that returns a promise which is either rejected or resolved.所以,我有这个函数 fetchData() 返回一个被拒绝或解决的承诺。 If promise resolves how can i render it on the page?如果 promise 解决了,我该如何在页面上呈现它?
function Fetchdata() {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) {
resolve(`resolved`);
} else {
reject(new Error("err"));
}
}, time);
});
}
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>
);
}
}
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.