Two issues jump out:
你的getData
永远不会返回任何东西,所以如果它不拒绝,它的promise (async
个函数总是返回一个promise )将以undefined
实现
错误消息清楚地表明,您正试图直接呈现promise getData
returns,而不是等待它结算,然后呈现实现值
Addressing #1: getData
should return the result of calling json
:
async getData(){
const res = await axios('/data');
return await res.json();
}
Addressig#2:我们必须看到您的更多代码,但从根本上说,您不能这样做
<SomeElement>{getData()}</SomeElement>
.因为这并不需要等待决议.相反,您需要使用getData
来设置状态:
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
...and use that state when rendering:
<SomeElement>{this.state.data}</SomeElement>
Update: Now that you've shown us your code, you'd need to do something like this:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
Futher update: You've indicated a preference for using await
in componentDidMount
rather than then
and catch
. You'd do that by nesting an async
IIFE function within it and ensuring that function can't throw. (componentDidMount
itself can't be async
, nothing will consume that promise.) E.g.:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
(async () => {
try {
this.setState({data: await this.getData()});
} catch (e) {
//...handle the error...
}
})();
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}