我需要向 API 发出请求,并且仅在呈现我的页面之后。为此,我使用了异步函数和返回方法,我曾经 promise 过,但我得到了错误:
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>
)
}
}
}
我认为最好的是使用 promise。怎么固定?谢谢
最佳答案
您不能在渲染中获取数据和 promise 。您应该将所有 API 调用移动到 componentDidMount
并且渲染应该只返回元素。
componentDidMount() {
this.getRequest()
.then((data) => { this.setState({ data }) })
}
render() {
return(
<div>
{this.state.data}
</div>
)
}
如评论中所述,对于 SSR,您可以尝试使用 getDerivedStateFromProps
代替 componentDidMount
。这将需要 React v16.3 及更高版本。
关于javascript - promise 返回时渲染没有返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53053844/