[英]Nothing was returned from render at promise return
I need to make a request to API and only after render my page. 我只需要在呈现页面后向API发出请求。 For this, I used async function and in return method, I used to promise, but I get the error:
为此,我使用了异步函数,并在return方法中使用了诺言,但出现了错误:
Nothing was returned from render.
class Main extends Component {
constructor(props) {
super(props)
this.data = []
}
async getRequest() {
const response = await fetch({'http://my url'})
const data = await response.json();
//exampe
this.data = data[0]
return respons
}
render() {
this.getRequest()
.then((data) => {
return(
<div>
{this.data}
</div>
)
}
}
}
I think the best, is use promise. 我认为最好的是使用承诺。 How fixed?
如何固定? Thanks
谢谢
You cannot data fetches and promises in your render. 您无法在渲染中进行数据获取和承诺。 You should move all the API calls to
componentDidMount
and render should be just returning the elements. 您应该将所有API调用移至
componentDidMount
并且render应该只是返回元素。
componentDidMount() {
this.getRequest()
.then((data) => { this.setState({ data }) })
}
render() {
return(
<div>
{this.state.data}
</div>
)
}
As noted in comments, for SSR, you can try using getDerivedStateFromProps
in place of componentDidMount
. 如注释中所述,对于SSR,您可以尝试使用
getDerivedStateFromProps
代替componentDidMount
。 This will require React v16.3 and above. 这将需要React v16.3及更高版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.