我有一个类仪表板组件,它componentDidMount()
使用从路由接收的道具从多个 API 中获取数据并呈现图表。
componentDidMount() {
this.urls = ChartProps[this.chart].api;
this.title = ChartProps[this.chart].titles;
Promise.all(
urls.map(url =>
fetch(url)
.then((res) => res.json())
.catch(error => console.log('There was a problem!', error))
))
.then((json) => {
this.formatJsonForChart(json);
});
}
现在在同一个组件上接收到来自不同路由的不同道具。
<BrowserRouter>
<Navlist/>
<Routes>
<Route path="/" element={<Dashboard element={<Dashboard chart='chart1'/>} />} />
<Route path="/chart2" element={<Dashboard chart='chart2'/>} />
<Route path="/chart3" element={<Dashboard chart='chart3'/>} />
<Route path="/chart4" element={<Dashboard element={<Dashboard chart='chart4'/>} />} />
<Route path="*" element={<ErrorPage />} err='404' />
</Routes>
</BrowserRouter>
所有获取数据的 API 都基于接收到的 props。这里的问题是渲染图表的函数在 componentDidMount() 中被调用,因此它在第一次路由点击时工作正常。但是,当单击其他路线时,它不会调用componentDidMount()
,因为组件已经安装,因此图表不会更新,请单击其他路线。
可以采取哪些替代方法?