2017-06-28 33 views
1

我正在構建一個簡單的電子反應組件。 該組件查詢啓用網絡接口,將數據推送到該狀態並呈現給DOM。該組件不起作用,因爲此錯誤: 「Uncaught TypeError:無法讀取此行的屬性'狀態未定義':
」data = this.state.data.slice();「 爲什麼this.state未定義?我有沒有想念約束力?感謝您的任何建議。ReactJS:this.state在生命週期鉤子上是未定義的

import React from "react"; 
import os from "os"; 

export default class GetInterfaces extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      data: [] 
     }; 
    }; 

    componentDidMount() { 
     let ifaces = os.networkInterfaces(); 
     Object.keys(ifaces).forEach(function (ifname) { 
      let data; 
      ifaces[ifname].forEach(function (iface) { 
       if (iface.internal === true || iface.family === "IPv6") { 
        return; 
       } 
       let networkInterface = { 
        name: ifname, 
        mac: iface.mac, 
        ip: iface.address 
       }; 
       data = this.state.data.slice(); 
       data.push(networkInterface); 
       this.setState({ data: data }); 
      }); 
     }); 
    } 

    render() { 
     const networkInterfaces = this.state.data.map((networkInterface, index) => 
      <ListGroupItem key={index}> 
       <i class="fa fa-wifi"></i> 
       <span>{networkInterface.name}</span> 
       <input type="checkbox"></input> 
      </ListGroupItem> 
     ); 

     return (
      <div> 
       {networkInterfaces} 
      </div> 
     ); 
    } 
} 
+0

很遺憾貧困文本格式! – Scr3w

+0

forEach功能的綁定問題,看到重複,你就會知道如何解決它 –

回答

0

我覺得「這個」正成爲綁定在.forEach功能,所以你可以嘗試之前保存上下文的伎倆像這樣

componentDidMount() { 
 
    let ifaces = os.networkInterfaces(); 
 
    let that = this; // Note the saving of the context 
 
    
 
    Object.keys(ifaces).forEach(function (ifname) { 
 
     let data; 
 
     ifaces[ifname].forEach(function (iface) { 
 
      if (iface.internal === true || iface.family === "IPv6") { 
 
       return; 
 
      } 
 
      let networkInterface = { 
 
       name: ifname, 
 
       mac: iface.mac, 
 
       ip: iface.address 
 
      }; 
 
      data = this.state.data.slice(); 
 
      data.push(networkInterface); 
 
      that.setState({ data: data }); // And then using the saved context 
 
     }); 
 
    }); 
 
}

+0

哇,這是沒有提到的任何地方!哪些函數會覆蓋這個? – Scr3w

0

這種情況因爲你正在失去你的this內部環境forEach請致電

as docs說,你可以通過附加參數forEach,這是thisArg

componentDidMount() { 
    let ifaces = os.networkInterfaces(); 
    Object.keys(ifaces).forEach(function (ifname) { 
     ... 
    }, this); 
}