reactjs - 在 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});
};
解决方案
未经测试,但我认为您必须检查并等待道具被定义。像这样的东西。
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"]}
/>
);
推荐阅读
- python - Plotting every 30th file of a list
- python - Group by with lists in Dataframe
- javascript - Cannot delete item from CosmosDB
- r - ggalluvial: identical strata order of the first and second axis
- python - What is causing fluctuations in the training accuracy in a categorization problem
- apache-spark - Applying different filters on different rows of a spark dataframe
- reactjs - Is it possible to add a row of Input controls to Ant table for searching purposes. Please refer the Image attached
- devops - Devops 实施 -CI CD
- sql - 如何从 PostgreSQL 1:n 表生成 XML 响应?
- python - 无法将数组附加到列表中