ReactJS:this.state在生命周期钩子

时间:2017-06-28 15:43:14

标签: reactjs

我正在构建一个简单的电子反应组件。 此组件查询启用的网络接口,将数据推送到状态并将其呈现给DOM。由于此错误,该组件不起作用: “未捕获的TypeError:无法在此行读取未定义的属性'状态':
    “data = this.state.data.slice();” 为什么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>
        );
    }
}

2 个答案:

答案 0 :(得分:0)

我认为“this”在.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
        });
    });
}

答案 1 :(得分:0)

这是因为您在this电话

中丢失了forEach个背景信息

正如docs所述,您可以将其他参数传递给forEach thisArg

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