一个反应组件,它获得父状态的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});
};
答案 0 :(得分:0)
未经测试,但我认为您必须检查并等待定义道具。像这样的东西。
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"]}
/>
);