我正在構建一個簡單的電子反應組件。 該組件查詢啓用網絡接口,將數據推送到該狀態並呈現給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>
);
}
}
很遺憾貧困文本格式! – Scr3w
forEach功能的綁定問題,看到重複,你就會知道如何解決它 –