0

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.

4

1 回答 1

0

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>
于 2016-10-08T14:19:18.217 回答