Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
782 views
in Technique[技术] by (71.8m points)

javascript - Render async component in React Router v4

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...