javascript - 承诺返回时渲染没有返回任何内容
问题描述
我需要向 API 发出请求,并且只有在呈现我的页面之后。为此,我使用了异步函数和返回方法,我曾经承诺,但我得到了错误:
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>
)
}
}
}
我认为最好的,是使用承诺。怎么固定?谢谢
解决方案
您不能在渲染中获取数据和承诺。您应该将所有 API 调用移动到componentDidMount
并且渲染应该只是返回元素。
componentDidMount() {
this.getRequest()
.then((data) => { this.setState({ data }) })
}
render() {
return(
<div>
{this.state.data}
</div>
)
}
如评论中所述,对于 SSR,您可以尝试使用getDerivedStateFromProps
. componentDidMount
这将需要 React v16.3 及更高版本。
推荐阅读
- linux - 一个进程的孙子和曾孙
- google-cloud-firestore - 等到使用 Google/Fb 身份验证创建 FireStore 用户
- android - Google Play 商店:保留原始版本签名
- pine-script - 打印水平线斐波那契数:收盘价上方一个值,收盘价下方一个值
- angular - 如何在角度表中添加验证器?
- visual-studio-code - 如何在本地vscode中调试远程服务器上的python文件
- msal - 如何针对 Azure AD 验证 Angular 应用发送到后端 API 的令牌?
- reactjs - 如何定义 useState 嵌套数组类型
- html - Bootstrap 4 - 使表头具有粘性
- shell - 删除 cron 作业及其评论,由 Puppet 通过 awk/sed 创建的环境