我正在尝试在 d3.js v5 地图上查看城市名称 我尝试了一些解决方案,因此无需工具提示即可“仅查看城市名称”,但在React “您无法更新已卸载的组件” 中遇到以下错误
在我当前的代码(在基于类的组件中)下面,我尝试使用钩子无济于事,所有这些概念对我来说都是新的。
// ... imports
class MapPathHolder extends Component {
constructor(props) {
super(props);
this.state = {
algyData: null,
toCity: "Algiers",
};
}
navigateToCity = () => {
this.props.history.push("/ToCityProducts");
};
componentWillMount() {
d3.json("algy.json").then((algyData) => {
this.setState({
algyData,
});
});
}
componentDidUpdate() {
const { width, height } = this.props;
const dz = this.state.algyData;
const svg = d3.select(this.refs.anchor);
var projection = d3
.geoEquirectangular()
// .parallels([29.5, 45.5])
.scale(1900.347057471)
.center([3, 40])
.translate([width / 1.4, height / 9]);
const path = d3.geoPath().projection(projection);
const g = svg.append("g");
g.append("g")
.attr("fill", "#4b4b4b")
.attr("cursor", "pointer")
.selectAll("path")
.data(
topojson.feature(dz, dz.objects.collection).features
)
.join("path")
.attr("stroke", "#A8846A")
.attr("stroke-width", 1)
.attr("d", path)
.on("click", (d) => {
this.props.postCity(d.properties.name);
this.navigateToCity();
})
.on("mouseover", function (d) {
d3.select(this).attr("fill", "orange");
})
.on("mouseout", function (d) {
d3.select(this).attr("fill", "#4b4b4b");
})
.append("title")
.text((d) => d.properties.name);
g.append("path")
.attr("fill", "none")
.attr("stroke-linejoin", "round")
.attr(
"d",
path(topojson.mesh(dz, dz.objects.collection, (a, b) => a !== b))
);
// error occurs after adding this line
g.append("title").text((d) => d.properties.name);
}
render() {
const { algyData, toCity } = this.state;
if (!algyData) {
return null;
}
return <g ref="anchor" />;
}
}
// ... mapState/DispatchToProps()
export default withRouter(
connect(mapStateToProps, mapDispatchToProps)(MapPathHolder));