javascript - ReactJS 映射函数错误
问题描述
在我单击提交按钮后,一个查询会转到 Neo4j 数据库并发送回响应。此外,当单击按钮时,另一个函数正在将该数据发送到 Graph 函数{this.state.submit && this.displayElements()}
。一旦进入 Graph 函数,我试图渲染一个图形,但 React 说 map 是未定义的。但是,来自 Graph 内部的道具控制台日志显示:{data:{action: "Changed", timestamp: 1499348050, object: Array(1), Second: Array(1), __typename: "action", …}
. 我在 map 之前尝试过不同的组合,但似乎没有任何效果(this.props.nodes、this.state.action 等)。
显示功能(通过 props 作为节点发送数据)
displayElements = () => {
const {data:{loading, error, action}} = this.props;
console.log(this.props);
if(loading) {
return <option disabled>Loading...</option>;
}else if (error){
return<p>Error!</p>;
}
return (
<Graph nodes={this.data}/> <--Sending data to Graph via props as nodes
);
}
图形功能
class Graph extends React.Component {
constructor(props) {
super(props);
this.state = {nodes: this.props};
console.log(this.props + "graph")
}
componentDidMount() {
this.force = d3.forceSimulation(this.state.nodes)
.force("charge",
d3.forceManyBody()
.strength(this.props.forceStrength)
)
.force("x", d3.forceX(this.props.width / 2))
.force("y", d3.forceY(this.props.height / 2));
this.force.on('tick', () => this.setState({nodes: this.state.nodes}));
}
componentWillUnmount() {
this.force.stop();
}
render() {
return (
<svg width={this.props.width} height={this.props.height}>
{this.state.nodes.action.map((node, index) =>(
<circle r={node.r} cx={node.x} cy={node.y} fill="red" key={index}/>
))}
</svg>
);
}
}
export default Graph;
解决方案
map 用于数组,但您传递的对象{data:{action: "Changed", timestamp: 1499348050, object: Array(1), Second: Array(1), __typename: "action", …}
一个解决方案可以是Object.keys(this.state.nodes.action).map(()=>{...}
{Object.keys(this.state.nodes.action).map((node, index) =>(
<circle r={node.r} cx={node.x} cy={node.y} fill="red" key={index}/>
))}
推荐阅读
- python - 使用python 3的GCP授权会话获取方法
- c# - C# Canvas 不会增加 int 变量
- sql - 用于 IP 地址或 inet 类型的 Postgres“不包含在”运算符中
- php - Magento 2 - 控制器返回空白页
- xamarin.forms - 有没有办法隐藏顶部标签栏?
- javascript - 如何从响应数据 reactjs 创建 csv/excel 文件
- ios - 无法使用完成处理程序将类型“()”的值转换为预期的参数类型“()-> Void”
- javascript - 限制插件中创建的元素javascript的数量
- java - 当条件的一部分时,java新文件不返回布尔值
- java - 控制中心未创建消费者组 - Kafka