【问题标题】:ReactJS/Javascript: componentDidMount() and renderReactJS/Javascript:componentDidMount() 和渲染
【发布时间】:2018-08-25 07:15:24
【问题描述】:

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);

【问题讨论】:

    标签: javascript reactjs graphql react-apollo


    【解决方案1】:

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

    正如the reference 所说:

    componentDidMount() 在组件安装(插入到树中)后立即调用。需要 DOM 节点的初始化应该放在这里。如果您需要从远程端点加载数据,这是一个实例化网络请求的好地方。

    this.props.data 目前未定义。

    虽然render 钩子在每次重新渲染时触发。该问题没有显示组件的使用方式,但预计&lt;Graph data={...} 中的data 值会异步定义,render 中的console.log(this.props.data) 反映了这一点。

    【讨论】:

    • 我在语法上遇到了困难,你能提供一个我上面的 D3 代码的例子吗?我对 React 和 D3 非常陌生。
    • 我无法让它工作,因为它只是更大的一部分。这就是stackoverflow.com/help/mcve 的意义所在。 graphql(..) export 是如何使用的?语法到底有什么问题?这基本上就是你的情况,stackblitz.com/edit/react-fsv6iu。请注意,data 最初也将在 render 中未定义。
    • 可能是的。我仍然不确定你在寻找什么例子。你手头已经有了工作的例子,不是吗?您发布的代码对我来说似乎没问题,并且您描述的行为是预期的。我更新了stackblitz.com/edit/react-fsv6iu,注意如果你需要放一些需要关注this.props.data的逻辑,你需要把它放到componentDidMountcomponentDidUpdate中。
    • 我不确定到底是什么问题。 点击提交按钮后,程序正常运行,提交按钮向下移动,但屏幕为空白?这与您最初的问题有很大不同,当然需要stackoverflow.com/help/mcve 来反映您当前的情况,最好是一个可行的演示,因为它需要调试。
    • 我不使用 GraphQL。您可以查看apollographql.com/docs/graphql-tools/mocking.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-04
    • 2019-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 1970-01-01
    相关资源
    最近更新 更多