[英]ReactJS/Javascript: componentDidMount() and 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);
安装组件时,将同步调用componentDidMount
挂钩。 重新渲染时不会调用它。
作为参考说明:
挂载组件(插入树中)后立即调用componentDidMount()。 需要DOM节点的初始化应在此处进行。 如果需要从远程端点加载数据,这是实例化网络请求的好地方。
目前尚未定义this.props.data
。
虽然render
钩子在每次重新渲染时都被触发。 这个问题没有显示组件的使用方式,但是可以预期<Graph data={...}
中的data
值是异步定义的,而render
console.log(this.props.data)
反映出来。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.