【问题标题】:Pass Javascript object as prop in React server side rendering在 React 服务器端渲染中将 Javascript 对象作为道具传递
【发布时间】:2019-11-01 19:38:50
【问题描述】:

我正在使用 ReactJS.net 来渲染反应服务器端

下面是我的cshtml文件中的代码

@Html.ReactRouter("RootComponent", new {services="service" }, containerId: "containerID")

这里我需要将服务传递给子组件。我还在入口点文件中声明了该对象

import service from '../../src/components/service.jsx';

global.service = service ;

有没有办法访问那个对象

【问题讨论】:

    标签: javascript reactjs .net-core server-side-rendering reactjs.net


    【解决方案1】:

    应该是 = 而不是 :

    @Html.ReactRouter("RootComponent", new {services = "service" }, containerId: "containerID")
    

    上面写的意思是,在您的RootComponent 中,您将能够在props 中访问services
    所以,它会是这样的

    class RootComponent extends React.PureComponent {
      // ...
    
      render () {
        const { services } = this.props;
        // ...
      }
    }
    

    function RootComponent ({ services }) {
      // ...
    }
    

    【讨论】:

    • 输入错误我确实编辑了我的问题,问题是在服务器端呈现它时,“服务”道具未定义,并且 HTML 未在浏览器上呈现。 “服务”未定义是我在控制台中遇到的错误
    • 您在代码中的哪个位置收到该错误?当你尝试访问services时在什么地方?
    • services 在根组件中作为 this.props.services 访问,我知道它是未定义的
    • 哦。我觉得我明白了。你先import service ... 然后global.service = service 然后你想把它传递给RootComponent?
    • 是的,正确。关键是在 cshtml 即服务器端无法访问该变量,并且它得到未定义的浏览器控制台
    猜你喜欢
    • 2015-11-06
    • 1970-01-01
    • 2018-08-03
    • 1970-01-01
    • 2015-05-07
    • 2019-03-20
    • 2021-09-08
    • 2020-06-29
    • 2019-10-05
    相关资源
    最近更新 更多