简体   繁体   English

React-Router服务器端渲染和Ajax获取数据

[英]React-router server-side rendering and ajax fetching data

I'm trying to implement react-router in my project and experiencing huge concept misunderstanding . 我正在尝试在我的项目中实现react-router并遇到巨大的概念误解。 For some of components in my app I need to fetch data from server. 对于我的应用程序中的某些组件,我需要从服务器获取数据。 Previously I did it with this code: 以前我是用以下代码完成的:

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

placed in componentDidMount or in onClick functions but now, in order to make server routing, all requests go to my routing file. 放置在componentDidMount或onClick函数中,但现在,为了进行服务器路由,所有请求都转到我的路由文件中。

How do I fetch data? 如何获取数据?

This is routing part of my server: 这是我服务器的路由部分:

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

This is routes.js 这是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>

); );

And let's say I need to fetch some data in child of one of children of firstPageChild in onButtonClick function. 假设我需要在onButtonClick函数的firstPageChild子级之一的子级中获取一些数据。 I can't prerender data and send with markup, so how should I do that? 我无法预渲染数据并发送带有标记的消息,那么该怎么办呢?

I believe you have found the answer. 我相信您已经找到了答案。 But please let me answer, in case someone has the same problem (like I did, this morning). 但是,请允许我回答,以防有人遇到相同的问题(就像我今天早上一样)。

  1. You should move the 404 error handling out of your "match react router" function, 您应该将404错误处理移出“匹配反应路由器”功能,
  2. Add the third parameter "next" to the return function #1 above, 将第三个参数“ next”添加到上面的返回函数#1中,
  3. Place your code to return AJAX data below this function. 将您的代码放置在此函数下方以返回AJAX数据。
  4. Create a route to handle the 404 not found error and place it on bottom. 创建一条路由来处理404 not found错误并将其放置在底部。

So your code will be like this: 因此,您的代码将如下所示:

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

It seems i've figured it out. 看来我已经知道了。 Apparently if app.get('*') stands after other requests it gonna catch only others and it totally makes sense. 显然,如果app.get('*')在其他请求之后仍然存在,那么它将仅捕获其他请求,这完全有道理。

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

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