首页 > 解决方案 > 在 React 中将 props 绑定到父状态

问题描述

一个反应组件,它获取父状态的 2 个属性作为道具来制作图形的 svg,

        const lines =
        Object.keys(this.props.nodes).length !== 0 &&
        this.props.input.map(line =>
            <line
                id={`${line[0]}${line[1]}`}
                x1={this.props.nodes[line[0]]["x"]}
                x2={this.props.nodes[line[1]]["x"]}
                y1={this.props.nodes[line[0]]["y"]}
                y2={this.props.nodes[line[1]]["y"]}
            />
        );

问题是由于输入最初是空对象我在填充行时出错我试图通过添加第一行来修复它,但每次输入更改时我仍然得到以下错误“TypeError:无法读取未定义的属性'x'”

父状态:

state = {
    input: [],   // sample : [[A,B]]
    nodes: {},   // sample : {A : {x:100, y: 150}, B : {x:200, y: 350}}
};

父图形创建函数(由按钮触发):

    createGraph = () => {
    let newNodes = {};
    this.state.input.forEach(line => {
        for (let i = 0; i < 2; i++) {
            let value = line[i];
            if (
                // !(value in this.state.nodes) &&
                value !== undefined &&
                value !== ""
            ) {
                newNodes[value] = this.randomPosition();
            }
        }
    });
    this.setState({nodes: newNodes});
};

标签: reactjsreact-props

解决方案


未经测试,但我认为您必须检查并等待道具被定义。像这样的东西。

    const lines =
    Object.keys(this.props.nodes).length !== 0 && this.props.nodes[line[0]] && this.props.nodes[line[1]] &&
    this.props.input.map(line =>
        <line
            id={`${line[0]}${line[1]}`}
            x1={this.props.nodes[line[0]]["x"]}
            x2={this.props.nodes[line[1]]["x"]}
            y1={this.props.nodes[line[0]]["y"]}
            y2={this.props.nodes[line[1]]["y"]}
        />
    );

推荐阅读