最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Render async component in React Router v4 - Stack Overflow

programmeradmin0浏览0评论

I want to render a component based on the payload it receives from an api like below

<Route path="/foo/bar" render={() => {
  return (get('/some/api').then((res) => {
    return <Baz data={res.data} />
          }).catch((err) => console.log))
        }} />

But I'm getting the error:

Objects are not valid as a React child (found: [object Promise]). If you 
meant to render a collection of children, use an array instead. 

even when I do wrap Baz in []

I want to render a component based on the payload it receives from an api like below

<Route path="/foo/bar" render={() => {
  return (get('/some/api').then((res) => {
    return <Baz data={res.data} />
          }).catch((err) => console.log))
        }} />

But I'm getting the error:

Objects are not valid as a React child (found: [object Promise]). If you 
meant to render a collection of children, use an array instead. 

even when I do wrap Baz in []

Share Improve this question edited Dec 18, 2017 at 23:58 JJJ 3,3325 gold badges30 silver badges45 bronze badges asked Dec 18, 2017 at 23:44 stackjleistackjlei 10k19 gold badges73 silver badges124 bronze badges 1
  • 3 render is synchronous. you need to have some state that you set from the response of your api call. there are many ways to do this, many of them very simple, but at a minimum you need to use state somewhere to handle the api response – azium Commented Dec 18, 2017 at 23:51
Add a comment  | 

1 Answer 1

Reset to default 16

unfortunately with the latest version of React - 16. Async rendering is not an option yet.

With React Router v4, the render props of Route component expects a valid React Element or array of React Elements to be returned, therefore, it doesn't accept the Promise object return from your function.

However, it's not impossible to achieve what you want with the current version of React and React Router. You just need to tweak your code a little bit. Instead of returning a Promise, your render should return a React Component, then you can do conditional rendering based on async value inside that component.

It should look like:

<Route path="/foo/bar" render={BazWrapper} />


class BazWrapper extends React.Component {

    // Do asynchronous action here
    async componentDidMount() {
       try {
          const apiValue = await get('/some/api');
          this.setState({ apiValue })
       } catch(err) {
          // error handling
       }
    }

    render() {
        const { apiValue } = this.state; 
        return <Baz data={apiValue} />;
    }

}

By calling setState after the asynchronous call finish, you let React Component know that the data is ready and it's should re-render the component.

发布评论

评论列表(0)

  1. 暂无评论