【问题标题】:Webpack rendering: "window is not defined"Webpack 渲染:“未定义窗口”
【发布时间】:2017-04-25 13:40:56
【问题描述】:

我使用 MERN – https://github.com/Hashnode/mern-starter (react, redux, webpack, nodejs, express) 还有组件 react-sound – https://github.com/leoasis/react-sound

当我包含组件时

import Sound from 'react-sound';

然后尝试启动服务器,我有来自 webpack 服务器渲染的"window is not defined" 错误。

但是如果我注释掉这一行并启动服务器,一切都会好起来的。之后我可以取消注释该行并且组件将起作用,因为当服务器运行时,更改不会触发服务器渲染(仅前端渲染)。

如果我尝试

if (typeof window !== 'undefined') {
    const Sound = require('react-sound');
}

在渲染中

render() {
    return (
        <div>
            <Sound playStatus={Sound.status.STOPPED} url="" />
        </div>
    );
}

我在前端渲染时出现ReferenceError: Sound is not defined 错误(在 webpack 之后)。

更新:

如果我尝试(var,而不是const

if (typeof window !== 'undefined') {
    var Sound = require('react-sound');
}

我的正面渲染出现TypeError: Cannot read property 'status' of undefined 错误。

【问题讨论】:

  • 在 if 块内定义 const Sound 将范围限制在该块内。带上 var Sound =null;在 if 之外,然后在 if 中设置值。

标签: node.js reactjs webpack soundmanager2 mern


【解决方案1】:

看来你不能在浏览器环境之外使用 react-sound。

解决办法可以如下:

let SoundEl;
if (typeof window !== 'undefined') {
  import Sound from 'react-sound';
  SoundEl = <Sound playStatus={Sound.status.STOPPED} url="" />
} else {
  SoundEl = <div></div>
}

...

render() {
  return (
    <div>
      {SoundEl}
    </div>
  )
}

【讨论】:

  • Invariant Violation:元素类型无效:期望字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。检查 ... 的渲染方法
  • 尝试 const Sound = require('react-sound').default 或从 'react-sound' 导入声音(请参阅更新的答案)
  • 很抱歉,问题出在
    中,如果它像 {SoundEl} 一样呈现,它可以正常工作,但你不必将其设为无状态组件(查看答案更新)facebook.github.io/react/docs/…
  • 无法读取未定义的属性“状态”。因为(我不知道为什么)它只适用于 import Sound from 'react-sound';要求不想工作
猜你喜欢
  • 1970-01-01
  • 2018-08-13
  • 2018-10-29
  • 1970-01-01
  • 1970-01-01
  • 2020-11-16
  • 2021-12-18
  • 2017-12-30
  • 1970-01-01
相关资源
最近更新 更多