【问题标题】:TypeError: Cannot read property 'userAgent' of undefinedTypeError:无法读取未定义的属性“userAgent”
【发布时间】:2017-10-13 18:53:12
【问题描述】:

我正在尝试将 react-slick slider 集成到我的 ReactJS 应用程序中。

当我将它集成到一个新的演示应用程序中时,它按预期工作,但如果我将它集成到我自己的应用程序中,它会引发错误。 我使用 rails 作为后端。

当我尝试在组件中导入滑块时

 var Slider = require('react-slick'); 

它显示了一个错误。

错误日志(在 rails 中)是

| ExecJS::ProgramError - TypeError: Cannot read property 'userAgent' of undefined:|   execjs (2.7.0) 
lib/execjs/ruby_racer_runtime.rb:98:in `wrap_error'|   execjs (2.7.0) 
lib/execjs/ruby_racer_runtime.rb:15:in `rescue in block in initialize'|   execjs (2.7.0) 
lib/execjs/ruby_racer_runtime.rb:12:in `block in initialize' |   execjs (2.7.0) 
lib/execjs/ruby_racer_runtime.rb:75:in `block in lock'|   execjs (2.7.0) 
lib/execjs/ruby_racer_runtime.rb:73:in `lock'|   execjs (2.7.0) 
lib/execjs/ruby_racer_runtime.rb:9:in `initialize'|   execjs (2.7.0) 

编辑

我的代码中的其他一些地方我已经在下面的代码中编写了它,它工作正常

'use strict';

var React = require('react');
import logo from 'img/spark-logo.jpg'
var Carousel = require('nuka-carousel');
//import { NukaDecorate } from 'nuka-carousel-autoscroll';


class App1 extends React.Component{

  // mixins: [Carousel.ControllerMixin],
  render() {
    return (
      <Carousel>
        <img src={logo} alt="Smiley face" />
        <img src="http://placehold.it/1000x400/ffffff/c0392b/&text=slide2"/>
        <img src="http://placehold.it/1000x400/ffffff/c0392b/&text=slide3"/>   
      </Carousel>
    )
  }
}

module.exports = App1; 

【问题讨论】:

  • @Tushar 请查看编辑
  • the documentation 中所述,ExecJS 不支持require()
  • 您是否尝试过将 js 代码作为 &lt;script&gt; 标记放在某个主模板中?
  • 这很有趣。那么,您当前的应用和圆顶应用之间的设置有何不同?

标签: javascript ruby-on-rails reactjs react-rails react-on-rails


【解决方案1】:

问题在于您显然是在尝试渲染您的应用服务器端(或者至少在非浏览器上下文中是必需的)。

其中一个依赖项是尝试访问全局navigator 对象的userAgent 属性,该对象仅在浏览器中定义。

为避免此问题,您可以尝试隔离插件,方法是仅在浏览器上要求它并检查 window 或您的 ruby​​ 中的等效项。

您也可以简单地将变量模拟为默认值,这样它就不会崩溃。简单定义如下:

global.navigator = {
  userAgent: 'node',
}

【讨论】:

  • 你尝试了什么?使用全局?你也想在 ruby​​ 中做 SSR 吗?
  • 我已经写了>> global.navigator = { userAgent: 'node', } 在上面的页面的乞求''use strict';行
  • 因为是使用它的模块,所以你必须确保在你的 react 应用程序初始化之前设置它,如果你能做到的话,它应该可以工作。 SSR 表示服务器端渲染,这是你在 ruby​​ 中想要实现的吗?
  • 我有 webpack.server 和 webpack.client.base.config 文件,我不知道我应该把你的解决方案放在哪里,
  • 你可以尝试使用DefinePlugin来设置导航器userAgent吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 2019-08-19
相关资源
最近更新 更多