【发布时间】: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