首页 > 解决方案 > 承诺返回时渲染没有返回任何内容

问题描述

我需要向 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>
               )
            }
     }
}

我认为最好的,是使用承诺。怎么固定?谢谢

标签: javascriptreactjs

解决方案


您不能在渲染中获取数据和承诺。您应该将所有 API 调用移动到componentDidMount并且渲染应该只是返回元素。

componentDidMount() {
    this.getRequest()
        .then((data) => { this.setState({ data }) })
}

render() {
    return(
        <div>
        {this.state.data}
        </div>
    )
}

如评论中所述,对于 SSR,您可以尝试使用getDerivedStateFromProps. componentDidMount这将需要 React v16.3 及更高版本。


推荐阅读