簡體   English   中英

如何在React組件中使用渲染的JSON數據

[英]How to use rendered json data in React component

我正在渲染一個頁面,並通過它傳遞一個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組件。 如何在react組件中訪問此數據?

一種方法是將對象添加到全局范圍並從組件中使用它:

<!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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM