
render函数中的控制台日志显示数据。componentDidMount()的console.log(this.props)未定义(嗯?)。那件事怎么可能?我不明白async在React中是如何工作的。
class Graph extends React.Component {
constructor(props) {
super(props);
this.state = { startTime:this.props.startTime,
endTime:this.props.endTime,
nodes:this.props.data
}
//console.log('graph data:', this.props.data)
}
componentDidMount() {
// console.log('nodes:', this.props.data)
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({data: this.props.data}));
console.log('setState:', this.props.data)
}
componentWillUnmount() {
this.force.stop();
}
render() {
// console.log('graph datas:', this.props.data)
return (
<svg width={this.props.width} height={this.props.height}>
{console.log('map data:', this.props.data)}
{Object.keys(this.props.data).map((node, index) =>(
<circle r={node.r} cx={node.x} cy={node.y} fill="red" key={index}/>
))}
</svg>
);
}//render
}//Component
export default graphql(getObjectsQuery,
{ options: (ownProps) => {
console.log(ownProps.startTime);
return ({ second: { startTime: ownProps.startTime,
endTime: ownProps.endTime
} })
} } )(Graph);发布于 2018-08-25 06:30:32
在挂载组件时同步调用componentDidMount钩子。它不会在重新渲染时调用。
正如the reference所说:
在挂载组件(插入到树中)后立即调用
componentDidMount()。需要DOM节点的初始化应该放在这里。如果需要从远程端点加载数据,这是实例化网络请求的好地方。
目前还没有定义this.props.data。
而render钩子在每次重新渲染时被触发。这个问题并没有说明组件是如何使用的,但是预期<Graph data={...}中的data值是异步定义的,而render中的console.log(this.props.data)反映了这一点。
https://stackoverflow.com/questions/52012185
复制相似问题