简体   繁体   English

承诺返回时,渲染未返回任何内容

[英]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.

相关问题 渲染没有返回任何内容 - Nothing was returned from render Home(…):渲染未返回任何内容。 这通常意味着缺少return语句。 或者,不渲染任何内容,则返回null - Home(…): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null 错误:渲染没有返回任何内容。 这通常意味着缺少 return 语句。 或者,不渲染任何内容,返回 null - Error: Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null unboundStoryFn(…):渲染没有返回任何内容。 这通常意味着缺少 return 语句。 或者,什么也不渲染,返回 null - unboundStoryFn(…): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null JAVASCRIPT:即使存在返回语句,也没有从渲染返回任何内容 - JAVASCRIPT: Nothing was returned from render even though return statement exists 渲染没有返回任何内容。 这通常意味着缺少返回语句 - Nothing was returned from render. This usally means a return statement is missing 渲染没有返回任何内容。 这通常意味着缺少返回语句 - Nothing was returned from render. This usually means a return statement is missing 反应:渲染没有返回任何内容 - React: Nothing was returned from render 为什么渲染未返回任何内容? - Why was nothing returned from render? 反应-渲染未返回任何内容 - React - nothing was returned from render
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM