echarts实例遇到的问题

为什么这里可以init两次

img


但是在子组件中又不行,这种问题要怎么解决

img

img

组件没有获取到dom的高度,使用display控制显隐的吗

以下答案引用自GPT-3大模型,请合理使用:

这是一个常见的问题,可能涉及到父子组件的生命周期问题。在父组件中,可以在挂载之后渲染echarts实例,而在子组件中渲染实例往往在更新之前就已经执行了,因此就会出现多次init情况。

为了解决这个问题,在父组件中可以使用shouldComponentUpdate()函数来检查当前组件是否是需要更新时才重新初始化echarts实例,代码如下:

```js
import React, { Component } from 'react'
import echarts from 'echarts' // 引入echarts

class Chart extends Component {
  constructor(props) {
    super(props)
    this.state = {
      chart: null,
    }
  }

  componentDidMount() {
    this.initChart()
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.data !== nextProps.data) {
      this.initChart()
    }
    return true // shouldComponentUpdate要返回true
  }

  initChart = () => {
    const chart = echarts.init(this.chartDom) // 初始化echarts实例
    // 然后,你可以通过props或state中拿到的数据来设置echarts实例
    this.setState({
      chart: chart,
    })
  }

  render() {
    return <div ref={dom => (this.chartDom = dom)} style={{ width: '100%', height: '300px' }}></div>
  }
}
export default Chart

```
如果我的回答解决了您的问题,请采纳我的回答

子组件里面的dom 打印一下 看看有没有拿到。vue中有href 没必要写原生了

init 两次 说明 你有两个 图表 。你看 他们 的 容器都不一样