小编典典

使用React-Engine和Express到客户端的服务器端变量

reactjs

我是React / React-
Engine的新手。我在服务器端有一个配置,我需要将某些值传递给客户端,但是为了获得正确的配置,我对NODE_ENV有依赖性。

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

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

这在服务器端工作得很好,但是由于我需要在客户端上引用这些对象中包含的某些值,所以我不需要(./config); 在我的React JSX中。

有什么简单的方法可以将这些东西传递给React?归根结底,如果我能以某种方式直接将“
config”直接传递到React中而不必担心客户端上的NODE_ENV,我会很高兴。

谢谢


阅读 269

收藏
2020-07-22

共1个答案

小编典典

在渲染之前将数据从服务器传递到客户端的最 常见 方法是将其嵌入到React渲染页面上的 全局JavaScript变量中

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

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-react-app.js"/> 
</body>
</html>

无论其 显然react-engine已经提供了它自己的方式发送数据做客户端:

组件渲染数据

送入组件进行渲染的实际数据是表达生成的renderOptions对象。

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

本例所示moviesjson只是传递给render:

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

然后,可能是在这一行上,借助框架的魔力,为您的组件提供了信息,然后List从中使用了它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>
    );
  }
});

因此,基本上 将您添加config到渲染调用中,它应该在您组件的中props

对于非常好奇的人:

事实上,正如我们可以看到这行开始,引擎合并renderOptionsres.locals最后传递下来反应。

// 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));

和:

return React.createElement(Component, merge({}, data, routerProps));
2020-07-22