首页 文章

React-router server-side 渲染和 ajax 获取数据

提问于
浏览
1

我正在尝试在我的项目中实现 react-router 并遇到巨大的概念误解。对于我的应用程序中的一些组件,我需要从服务器获取数据。以前我用这个代码做了:

$.get('/getSmData', options, function (result) {
      // set state with result or whatever
      }.bind(this));

放在 componentDidMount 或 onClick 函数中,但现在,为了进行服务器路由,所有请求都转到我的路由文件。

我如何获取数据?

这是我的服务器的路由部分:

var  renderToString = require( 'react-dom/server').renderToString
var  match = require('react-router').match
var RouterContext  = require('react-router').RouterContext
var routes = require('./routes')

app.get('*', function (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) {
        res.render('index', {
          react: renderToString(React.createElement(RouterContext, renderProps)),
          })
    } else {
      res.status(404).send('Not found')
    }
  })
})

这是 routes.js

module.exports=  (
<Router history={browserHistory}>
      <Route path='/' component={index.App}>
          <Route path='/firstPage' component={First}>
            <Route path=':firstPageChild' component={FirstCh}/>
          </Route>
          </Route>
          <Route path='/secondPage' component={Second}/>
        </Route>
  </Router>

);

并且假设我需要在 onButtonClick 函数中获取 firstPageChild 的子节点之子的一些数据。我无法预呈现数据并使用标记发送,那么我该怎么做?

2 回答

  • 2

    我相信你找到了答案。但请让我回答,万一有人有同样的问题(就像我今天早上做的那样)。

    • 您应该将 404 错误处理移出“匹配反应路由器”功能,

    • 将第三个参数“next”添加到上面的返回函数#1,

    • 放置代码以返回此函数下的 AJAX 数据。

    • 创建一个路径来处理 404 未找到错误并将其放在底部。

    所以你的代码将是这样的:

    app.get('*', function (req, res, next) {
           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) {
                  res.render('index', {react: renderToString(React.createElement(RouterContext, renderProps)),
                  })
              } else {
                  // release control to the next middleware, in this case your URL for catching AJAX data
                  next();
              }
           })
        })
    
        // return your AJAX data 
        app.get('/getSmData', function (req, res) {            
           res.send({ status: 'ok' });
        });
    
        // return 404 not found error 
        app.use(function (req, res) {            
           res.status(404).send('Not found');
        });
    
  • 0

    好像我已经弄明白了。显然,如果 app.get('*')代表其他请求,它将只捕获其他请求,这完全有道理。

相关问题