更新数据后,React / D3中的点击事件未更新

时间:2019-04-18 04:11:13

标签: reactjs d3.js mouseevent

我有一个React组件,可渲染一个D3条形图,可单击这些条。它会按预期工作,直到更新父状态。条形图正确更新,但条形图上的click事件仍绑定到先前的数据。我不确定这是否是我在React或D3或两者中做错的事情。任何帮助表示赞赏。

const DATA1 = [{"value":1}, {"value":1}]

const DATA2 = [{"value":3}, {"value":3}, {"value":3}, {"value":2}, {"value":2}]

const CLICK = 'chartClick'

function handleClick(data, i, els) {
  const element = els[i]

  const event = new Event(CLICK, {bubbles: true, detail: data})

  return element.dispatchEvent(event)
}

class D3Chart {
  constructor(selector) {
    this.svg = d3.select(selector).append('svg')
  }

  draw(data) {
    const xScale = d3.scaleLinear()
      .domain([0, d3.max(data.map(i => i.value))])
      .range([0, 500])

    const barGroups = this.svg.selectAll('.barGroup').data(data)

    const barGroupsEnter = barGroups.enter().append('g')
      .attr('class', 'barGroup')
      .attr('transform', (d, i) => {
        const y = (i * 25)

        return `translate(0, ${y})`
      })

    barGroupsEnter.append('rect')
      .attr('class', 'bar')
      .attr('height', 20)
      .attr('width', d => xScale(d.value))
      .on('click', handleClick)

    barGroups.exit().remove()
  }
}


class Chart extends React.Component {
  chartRef = React.createRef()

  componentDidMount() {
    const {data, onClick} = this.props

    this.chartRef.current.addEventListener(CLICK, onClick)

    this.chart = new D3Chart(this.chartRef.current)

    this.chart.draw(data)
  }

  shouldComponentUpdate(nextProps) {
    const {data} = this.props

    return !_.isEqual(data, nextProps.data)
  }

  componentDidUpdate() {
    const {data} = this.props

    this.chart.draw(data)
  }

  render() {
    return <div ref={this.chartRef}></div>
  }
}


class App extends React.Component {
  state = {data: DATA1}

  handleButtonClick = () => this.setState({data: DATA2})

  handleChartClick = (data, event) => console.log('data length on click', data.length)

  render() {
    const {data} = this.state

    console.log('data length on render', data.length)

    return (
      <React.Fragment>
        <button onClick={this.handleButtonClick}>Update Data</button>
        <Chart data={data} onClick={(event) => this.handleChartClick(data, event)} />
      </React.Fragment>
    )
  }
}

ReactDOM.render(<App />, document.querySelector('.root'))

初始渲染/单击的输出为:

"data length on render" 2
"data length on click" 2

数据更新后的输出为:

"data length on render" 5
"data length on click" 2

我希望后者是:

"data length on render" 5
"data length on click" 5

此处的Codepen示例:https://codepen.io/bohmanart/pen/QPQJdX

1 个答案:

答案 0 :(得分:0)

您可以尝试以下解决方案,将图表内的onclick事件更改为this.chartRef.current.addEventListener(CLICK, ()=>onClick(this.props.data.length);),将图表上的onClick道具更改为onClick={this.handleChartClick},然后将句柄图单击更改为handleChartClick = (data) =>{ console.log('data length on click', data);} < / p>

对于为什么要通过handleChartClick从Chart组件传递数据的情况,我不确定用例,当数据已经在App类状态下可用时。您可以只在this.state.data.length

中使用handleChartClick