React中D3图表组件点击按钮后无法更新问题排查
问题原因分析与修复方案
我一眼就看到问题出在componentDidUpdate的处理上!你在这个生命周期里直接把整个承载图表的<div>给删掉了:
componentDidUpdate() { d3.select(`#${this.props.graphID}`).remove() this.drawChart(); }
当你调用.remove()的时候,那个带有graphID的<div>元素直接从DOM中被移除了。接下来执行drawChart()时,d3.select(#${this.props.graphID})根本找不到任何元素,自然没法创建新的SVG图表,所以就出现了原有图表消失但新图表没出来的情况。
修复步骤
把componentDidUpdate里的移除逻辑改成清空<div>内部的内容,而不是删掉整个div:
componentDidUpdate() { // 清空容器内的所有元素,保留容器本身 d3.select(`#${this.props.graphID}`).selectAll("*").remove(); this.drawChart(); }
这样一来,承载图表的<div>还留在DOM里,drawChart()就能正常选择它并添加新的SVG元素了。
额外优化建议
另外,你的setRecommendations函数里多次调用this.setState,React会把这些异步更新合并成一次,虽然不影响功能,但可以优化成一次setState调用,让代码更简洁且减少组件更新次数:
setRecommendations(){ Promise.all([ getAlbums(), getArtists(), getGenres(), popularityData(), recommendations() ]).then(([albums, artists, genres, popData, recs]) => { this.setState({ topAlbums: albums[0], album_count: albums[1], topArtist: artists[0], artist_count: artists[1], topGenre: genres[0], genre_count: genres[1], popRange: popData[0], pop_count: popData[1], recommendations: recs }); }); }
内容的提问来源于stack exchange,提问作者Tyler Strouth
相关产品推荐
相关产品推荐

