Render async component in React Router v4

后端 未结 1 1206
轻奢々
轻奢々 2021-01-18 17:17

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

 {
  return (get(\'/some/api         


        
1条回答
  •  北海茫月
    2021-01-18 17:21

    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:

    
    
    
    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 ;
        }
    
    }
    

    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 讨论(0)
提交回复
热议问题