2016-07-05 100 views
1

我已經加載了js文件中的對等js,並且當我在我的瀏覽器的控制檯行上鍵入Peer時,它向我顯示該對象。 然而,當網頁加載完畢後,我得到: Chat.jsx:18未捕獲的ReferenceError:同行是沒有定義流星React Uncaught ReferenceError:Peer is not defined

export default class Chat extends React.Component{ 

constructor(){ 
super(); 

      // Create a Peer instance 
     window.peer = new Peer({ // the error is on this line 
     key: 'thisismykey', // get a free key at http://peerjs.com/peerserver 
     debug: 3, 
     config: {'iceServers': [ 
       { url: 'stun:stun.l.google.com:19302' }, 
       { url: 'stun:stun1.l.google.com:19302' }, 
      ]} 
     }); 
    } 

當我輸入對到控制檯我得到:

Function Peer(id, options) { 
    if (!(this instanceof Peer)) return new Peer(id, options); 
    EventEmitter.call(this); 
    // Deal with overloading 
    if (id && id.constructor == Object) { 
    optio… // etc 

我曾嘗試使用componentOnMount但也提供了相同的問題。

這是由於我在考慮加載.js文件。但我將它加載到索引文件中,與所有其他正在工作的.js文件相同。

<script src="assets/js/peer.js"></script>. 

我知道有一種不同的方式來加載文件,但其他的工作,所以我想知道爲什麼不這樣做。

有沒有辦法在組件準備就緒時運行代碼。

當我只是添加一個按鈕來調用/ /創建一個Peer實例代碼,它工作正常,整個事情的作品。所以js確實會被加載,只是在我思考的錯誤時間。

謝謝!

+0

你的意思是componentDidMount? – SlartyBartfast

回答

0

因爲您正在使用窗口對象(window.peer),所以您應該等待DOM呈現。

從陣營Docs

componentDidMount is called after the component is mounted and has a DOM representation. This is often a place where you would attach generic DOM events.


你可能有一個很好的理由在標籤加載腳本。如果你不這樣做,你可能會有更好的運氣,只要將它包含在你的包裹裏(see guide)。

meteor npm install --save peer 

然後

import peer from 'peer'; 
中的每個組件

您使用同行


然後像(window.peer刪除):

export default class Chat extends React.Component{ 

constructor(){ 
    super(); 
    this.state { 
     peer = new Peer({ 
      key: 'thisismykey', // get a free key at http://peerjs.com/peerserver 
      debug: 3, 
      config: {'iceServers': [ 
      { url: 'stun:stun.l.google.com:19302' }, 
      { url: 'stun:stun1.l.google.com:19302' }, 
     ]} 
    }; 
} 

componentWillMount() { 
    this.state.peer.on('open', (id) => { 
     console.log('My peer ID is: ' + id); 
     this.setState({ 
      my_id: id, 
      initialized: true 
     }); 
    }); 

    this.state.peer.on('connection', (connection) => { 
     console.log('someone connected'); 
     console.log(connection); 

     this.setState({ 
      conn: connection 
     },() => { 
      this.state.conn.on('open',() => { 
       this.setState({ 
        connected: true 
       }); 
      }); 

      this.state.conn.on('data', this.onReceiveData); 
     }); 
    }); 
} 

render() { 
    var result; 
    if(this.state.initialized){ 
     result = (
      <div> 
       <div> 
     Your PeerJS ID: <strong className="">{this.state.my_id}</strong> 
       </div> 
       {this.state.connected ? 'Your Connected' : 'Your Not Connected'} 
      </div> 
     ); 
    } else { 
     result = <div>Loading...</div>; 
    } 

    return result; 
} 

未測試

相關問題