【问题标题】:How to render component in react server side with async data如何使用异步数据在反应服务器端渲染组件
【发布时间】:2016-10-08 13:37:32
【问题描述】:

我搜索了很多,并没有找到任何实现来在反应服务器端异步加载数据,然后在没有任何通量(redux)实现的情况下渲染标记。 这是视图(api和视图一起):

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

路由器文件(router.js):

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

这就是我在服务器上使用的(使用 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");
    })
});

我知道一些基本的事情,将 api 调用附加到每个路由器 url,然后解析 renderToString()。但我不明白如何用 react-router 做到这一点。 我不想使用任何库、flux 或 redux 实现。

【问题讨论】:

    标签: javascript reactjs react-router server-rendering


    【解决方案1】:

    您可以使用react-router 中的getComponent 属性来处理这种情况。

    //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>
    

    【讨论】:

    • 这很有用。你知道如何在客户端共享这些数据吗?
    • 您可以使用react-router 中的match 函数将相同的routes 模块与window.location 匹配,并在@ 的回调中从react-dom 调用render 函数987654330@客户端函数
    猜你喜欢
    • 2016-07-04
    • 2017-01-14
    • 1970-01-01
    • 2019-02-09
    • 2018-10-02
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    相关资源
    最近更新 更多