2017-04-25 83 views
2

我使用MERN - https://github.com/Hashnode/mern-starter(反應,終極版,的WebPack,的NodeJS表達) 和組分反應聲 - https://github.com/leoasis/react-sound的WebPack渲染: 「沒有定義窗口」

當我包括組分

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> 
    ); 
} 

我對前面的渲染(之後的WebPack)ReferenceError: Sound is not defined錯誤。

UPDATE:

如果我嘗試(var,不const

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

我對前面的渲染TypeError: Cannot read property 'status' of undefined錯誤。

+0

限定內部的常量聲音如果塊限制了範圍,以該塊的內部。將var Sound = null;在if之外,然後在if中設置值。 – scrappedcola

回答

0

似乎你不能在瀏覽器環境之外使用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> 
) 
} 
+0

不可違反:元素類型無效:期望一個字符串(對於內置組件)或類/函數(對於複合組件),但得到:object。檢查渲染方法... – Luntegg

+0

嘗試const Sound = require('react-sound')。默認或導入來自'react-sound'的聲音(查看答案已更新) – dgrijuela

+0

再次出現同樣的錯誤。 – Luntegg