首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >componentDidMount()和render

componentDidMount()和render
EN

Stack Overflow用户
提问于 2018-08-25 05:56:47
回答 1查看 62关注 0票数 0

render函数中的控制台日志显示数据。componentDidMount()console.log(this.props)未定义(嗯?)。那件事怎么可能?我不明白async在React中是如何工作的。

代码语言:javascript
复制
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);
EN

回答 1

Stack Overflow用户

发布于 2018-08-25 06:30:32

在挂载组件时同步调用componentDidMount钩子。它不会在重新渲染时调用。

正如the reference所说:

在挂载组件(插入到树中)后立即调用

componentDidMount()。需要DOM节点的初始化应该放在这里。如果需要从远程端点加载数据,这是实例化网络请求的好地方。

目前还没有定义this.props.data

render钩子在每次重新渲染时被触发。这个问题并没有说明组件是如何使用的,但是预期<Graph data={...}中的data值是异步定义的,而render中的console.log(this.props.data)反映了这一点。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52012185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档