我在React中使用动态路由。 我正在从第三方API提取一些数据。我的动态路线是这样的
<Route path="/:id" component = {item} />
在item组件中,我在params.id
中获取了值,并使用该ID在
componentDidUpdate(){ fetchData(this.props.match.params.id);}
我现在遇到的问题是,每当我尝试从Item组件访问具有相同格式/:id
的另一条路线时,参数都会更改为传递的新ID,但仍保留旧内容ID。我相信未调用componentDidmount,因为我位于同一项目组件中。该组件没有重新安装,只是更新了。我该怎么办?
答案 0 :(得分:2)
您必须在componentDidMount
和componentDidUpdate
中使用类组件进行api调用。提取数据后,必须将其设置为组件状态才能直观地看到它。
componentDidmount() {
fetchData(this.props.match.params.id);
}
componentDidUpdate(prevProps, prevState){
if(prevProps.match.params.id !== this.props.match.params.id) {
fetchData(this.props.match.params.id);
}
}
如果您宁愿使用react hooks +功能组件,则将为您简化此过程。您可以使用useState
将数据保持在该状态。
import React, { useEffect } from "react";
const YourComponent = props => {
const { id } = props.match.params;
// This will run every time id changes.
useEffect(() => {
fetchData(id);
}, [id]);
return (
<>
Your api call
</>
);
};