【问题标题】:Server side data fetch with react-router使用 react-router 获取服务器端数据
【发布时间】:2016-05-24 22:09:56
【问题描述】:

我正在我的 express 应用程序的服务器上渲染我的 React-router。 这是我的代码

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

它有效。我可以在不刷新的情况下进行路由。 但是在我的组件被渲染之前我如何参考我的快速路由来查询我的数据库(不是 ajax 查询)..

【问题讨论】:

    标签: javascript express reactjs ecmascript-6 react-router


    【解决方案1】:

    您可以查询您的数据库并使用回调来捕获响应 Web 请求所需的变量,例如res。 或者,您可以使用生成器来yield 数据库中的结果。 您的解决方案对您使用的数据库和库非常重要。

    这是一个例子:

    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');
        }
      });
    });
    
    // ...
    

    【讨论】:

    • thanx for answer 我会尝试一下。但是如果我需要进行不同的查询,这取决于我是否会去 /users 等路线,它必须让所有用户......如果我会去 / user/1 它将获得一个 id 等于 1 的用户 ....在您的示例中,我可以进行一个选择查询。
    • 您使用的是快递吗?例如,如果您的路线是app.get('/user/:id', ...),您可以通过req.params.id 访问该ID。然后您可以使用此值进行查询。
    • 是的,我正在使用 Express。但你不明白)如何从 react 路由器引用我的 Express 路由?
    • 我将我的 Express 路由放到 routes/api 文件夹,因为当我在浏览器中引用 /users 时,它会从 Express 路由中抛出 json 响应 ..现在我想引用我的 /api/users express 路由并获取当我要去 react.sorry 的 /users 路线时从中获取数据
    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 2015-08-18
    • 2019-02-03
    相关资源
    最近更新 更多