本文介绍了使用React-Engine和Express的客户端的服务器端变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对React / React-Engine很新。我在服务器端有一个配置,我需要传递某些值到客户端,但是我依赖于NODE_ENV才能获得正确的配置。

  var config = {
local:{...}
production:{...}
}

module.exports = config [process.env.NODE_ENV]

哪些工作只是服务器端,但是因为我需要在客户端引用这些对象中包含的一些值,所以我不能(./ config);在我的React JSX中。



有没有什么简单的方法可以将这些东西传递给React?在一天结束的时候,如果我可以直接将config直接传递到React,而不用担心客户端的NODE_ENV,我会很高兴。



谢谢

解决方案

在渲染之前将数据从服务器传递到客户端的最常用的将其嵌入到您的React呈现的页面上的全局JavaScript变量中。



所以,例如,在中间件实际上,您的React应用程序实际上会渲染一些包含< script> 标签的模板,您可以添加信息并将其抓取到模板上:

  var config = require('../ config-from-somewhere'); 
app.get('/',function(req,res){
res.render('index',{config:JSON.stringify(config)});
});

和一个例子的胡子模板:

 < HTML> 
< body>
< script>
window.CONFIG = JSON.parse({{{config}}});
< / script>
< script src =my-reactions-app.js/>
< / body>
< / html>

HOWEVER 显然反应引擎已经提供了自己的客户端发送数据的方式:



正如你在,电影 json只是被传递给render:

  app.get('*',function(req,res){
res.render(req.url,{
movies:require './movies.json')
});
});

然后,通过框架的魔法的恩典,可能在,该信息是为您的组件提供的,然后是使用它从 props.movi​​es

  module.exports = React.createClass({
displayName :'List',

render:function render(){
return(
< div id ='list'>
< h1& / h1>
< h6>点击电影查看详情< / h6>
< ul>
{this.props.movi​​es.map(function(movie){
return(
< li key = {movie.id}>
< Router.Link to = {'/ movie /'+ movie.id}>
< ; img src = {mov ie.image} alt = {movie.title} />
< /Router.Link>
< / li>
);
})}

< / ul>
< / div>
);
}
});

所以,基本上添加你的配置到您的渲染调用,它应该在您的组件的道具中可用。



非常好奇:



的确,我们可以在,引擎合并 renderOptions res.locals 并最终将其传递给React。

  //创建将被馈送到React渲染的数据对象方法。 
//数据是快速的render选项和res.locals的$ m
//和有关'react-engine'的元信息
var data = merge({
__meta:{
//获取视图文件名的相对路径
视图:null,
markupId:Config.client.markupId
}
} ,omit(options,createOptions.renderOptionsKeysToFilter));

And:

 code> return React.createElement(Component,merge({},data,routerProps)); 


I'm reasonably new to React/React-Engine. I have a config on the server-side that I need to pass certain values of to client-side however I have a dependency on NODE_ENV in order to get the correct config out.

var config = {
    local: { ... }
    production: { ...}
}

module.exports = config[process.env.NODE_ENV]

Which works just fine server-side, however since I need to reference some of values contained in these objects on the client-side so I can't require(./config); in my React JSX.

Is there any easy way to pass this stuff into React? At the end of the day, I'd be happy if I could just pass the 'config' straight into React somehow without even having to worry about NODE_ENV on the client-side.

Thanks

解决方案

The most common way to pass data from the server to client before rendering is to embed it in a global JavaScript variable on the page where your React is rendering.

So, for example, in the middleware where you're actually rendering some template which includes your <script> tags with your React app, you could add the info and grab it on the template:

var config = require('../config-from-somewhere');
app.get('/', function (req, res) {
  res.render('index', {config: JSON.stringify(config)});
});

And an example mustache template:

<html>
<body>
<script>
  window.CONFIG = JSON.parse({{{config}}});
</script>
<script src="my-react-app.js"/>
</body>
</html>

HOWEVER apparently react-engine already provides its own way to send data do the client-side:

https://github.com/paypal/react-engine#data-for-component-rendering

As you can see in this example, the movies json is simply being passed into render:

app.get('*', function(req, res) {
  res.render(req.url, {
    movies: require('./movies.json')
  });
});

And then, by the grace of the framework's magic, probably on this line, the information is provided for your components and then the List uses it from props.movies.

module.exports = React.createClass({
  displayName: 'List',

  render: function render() {
    return (
      <div id='list'>
        <h1>Movies</h1>
        <h6>Click on a movie to see the details</h6>
        <ul>
          {this.props.movies.map(function(movie) {
            return (
              <li key={movie.id}>
                <Router.Link to={'/movie/' + movie.id}>
                  <img src={movie.image} alt={movie.title} />
                </Router.Link>
              </li>
            );
          })}

        </ul>
      </div>
    );
  }
});

So, basically add your config to your render call and it should be available in your component's props.

And for the very curious:

Indeed, as we can see on this line onwards, the engine merges renderOptions and res.locals and finally passes that down to React.

// create the data object that will be fed into the React render method.
// Data is a mash of the express' `render options` and `res.locals`
// and meta info about `react-engine`
var data = merge({
  __meta: {
    // get just the relative path for view file name
    view: null,
    markupId: Config.client.markupId
  }
}, omit(options, createOptions.renderOptionsKeysToFilter));

And:

return React.createElement(Component, merge({}, data, routerProps));

这篇关于使用React-Engine和Express的客户端的服务器端变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-07 10:01