如何在React组件

时间:2017-08-08 21:45:16

标签: javascript node.js reactjs express

我在get上渲染一个页面并用它传递一个json对象,如下所示:

/* GET home page. */
router.get('/', (req, res, next) => {
  const message = req.session.message;
  res.render('index', { data: message });
});

这是我的index.ejs视图:

<!DOCTYPE html>
<html>
  <head>
    <title>My Title</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <div id='react-app'> Loading &hellip;</div>
  </body>
  <script src="/javascripts/build.js"></script>
</html>

正在呈现的页面是index.js:

import React from 'react';

import { AppContainer } from 'react-hot-loader';
import { Provider } from 'react-redux';
import { render } from 'react-dom';

import 'bootstrap/dist/css/bootstrap.min.css';
import './css/msha.scss';

import Store from './store';
import TemplateContainer from './components/TemplateContainer';

const renderApp = (Component) => {
  render(
    <AppContainer>
      <Provider store={Store}>
        <Component />
      </Provider>
    </AppContainer>,
    document.querySelector('#react-app'),
  );
};

renderApp(TemplateContainer);

if (module && module.hot) {
  module.hot.accept('./components/TemplateContainer', () => {
    renderApp(TemplateContainer);
  });
}

正在呈现的页面包含反应组件。如何在react组件中访问此数据?

1 个答案:

答案 0 :(得分:2)

其中一种方法是将对象添加到全局范围并从组件中使用它:

<!DOCTYPE html>
<html>
  <head>
    <title>My Title</title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
  </head>
  <body>
    <div id='react-app'> Loading &hellip;</div>
    <script>
      window.data = <%- JSON.stringify(data) %>;
    </script>
    <script src="/javascripts/build.js"></script>
  </body>
</html>