【发布时间】:2020-10-16 18:14:58
【问题描述】:
一个反应组件,它获取父状态的 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"]}
/>
);
问题是由于输入最初是空对象,我在填充 lines 时出错,我尝试通过添加第一行来修复它,但每次输入更改时我仍然得到以下错误 “ 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});
};
【问题讨论】:
标签: reactjs react-props