简体   繁体   English

使用React-Router获取服务器端数据

[英]Server side data fetch with react-router

I am rendering my React-router on server in my express app. 我正在我的快速应用程序中的服务器上渲染我的React-router。 here is my code 这是我的代码

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

match({ routes, location: req.url }, (error, redirectLocation, renderProps) => {
console.log(renderProps)
if (error) {
  res.status(500).send(error.message)
} else if (redirectLocation) {
  res.redirect(302, redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
  let component = renderToString(<RoutingContext {...renderProps}/>);

  var html = renderToStaticMarkup(body(null,
      div({id: 'content', dangerouslySetInnerHTML: {__html:component}}),
      script({src: '/js/main.js'})
  ))
  res.end(html)
    } else {
      res.status(404).send('Not found')
    }
  })
});

and it works.I can route without refresh. 它可以正常工作。 but how i can refer to my express routes to make a queries to my database before my component will be rendered (not ajax queries).. 但是我如何引用我的快速路由以在呈现组件之前对数据库进行查询(不是ajax查询)。

You can query your database and use a callback which captures the variables you need to respond to the web request, eg res . 您可以查询数据库并使用回调函数来捕获需要响应Web请求的变量,例如res Alternatively, you can use generators to yield the result from your database. 另外,您可以使用生成器从数据库中yield结果。 Your solution will really matter on what database and library you're using. 您的解决方案实际上取决于您使用的数据库和库。

Here's an example: 这是一个例子:

const mysql = require('mysql');
let connection = mysql.createConnection({ ... });

// ...

app.use((req, res) => {
  match({ routes, location: req.url}, (error, redirectLocation, renderProps) => {
    if (error) res.status(500).send(error.message);
    else if (redirectLocation) res.redirect(302, redirectLocation.pathname + redirectLocation.search);
    else if (renderProps) {
      connection.query('SELECT 2 + 2 AS sample', (err, rows, fields) => {
        if (err) res.status(500).send(err);
        else {
          let fromDatabase = rows[0].sample;
          let component = renderToString(<RoutingContext {...renderProps} />);
          let html = renderToStaticMarkup(body(
            null,
            div({ id: 'content', dangerouslySetInnerHTML: { __html: component } }),
            script({ src: '/js/main.js' })
          ));
          res.end(html);
        }
      });
    } else {
      res.status(404).send('Not found');
    }
  });
});

// ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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