简体   繁体   中英

How to render component in react server side with async data

I searched a lot and didn't find any implementation to load data async in react server side before render the markup without any flux (redux) implementation. Here's the view (both api and views together):

class Home extends React.Component {
  constructor(props) {
    super(props); 
    this.state = {meta: []};
  }

  componentDidMount() {
    Request.get('http://example.com/api/users').then((resp) => {
      this.setState({meta: resp.body});
    });

  }

  render() {
    return (
      <div>
        {this.state.meta.map((m, i) => {
          <p key={i}>{m.user}</p>
        })}
    );
  }
}

The router file (router.js):

export default (
    <Route component={App} path="/">
        <IndexRoute component={Home}/>
    </Route>
);

And this is what I use on server (with react-router)

app.use((req, res) => {

    Router.match({routes: routes, location: req.url}, (err, redirectLocation, renderProps) => {
        if(err) res.status(500).send(err.message);

        else if(redirectLocation)
            res.status(302).redirect(redirectLocation.pathname + redirectLocation.search);

        else if(renderProps) {
                var html = ReactDOM.renderToString(<RouterContext {...renderProps}/>);
                res.render("layout", {body: html});
        }
        else res.status(404).send("Page not Found");
    })
});

I know some basic thing that attach api calls to each router url and then resolve the renderToString() after that. But I don't understand how to do that with react-router. I don't want to use any library or flux or redux implementation.

you can use getComponent prop in react-router to handle this situation.

//route.js
  function fetchAndGetComponent(location,callback){
    Request.get('http://example.com/api/users').then((resp) => {
      let meta = resp.body;
      callback(null,() => <Home meta={meta} />);
    });
  }

  <Route component={App} path="/">
        <IndexRoute getComponent={fetchAndGetComponent}/>
  </Route>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM