[英]How to load new axios data in react component
我有一個導航菜單,可以使用<Link to={"/entity"}>Entities</Link>
正確加載帶有 react-router 的組件
組件使用 axios 加載數據並將其顯示在表格中。 我正在努力完成的是在隨后單擊<link>
時加載新數據。
class List extends Component {
constructor() {
super();
this.state = { entities: [], loading: true};
}
componentDidMount() {
this.getData();
console.log('componentDidMount');
console.log(this.state.entities);
}
getData() {
axios.get(this.props.url).then(response => {
this.setState({ entities: response.data, loading: false})
})
}
render() {
...
}
這適用於加載一組數據。 但是,如果我編輯一行並再次打開列表,它將獲得最初檢索的內容。 給定該代碼,哪種行為是正確的,但我如何重新加載它? 我試過 componentDidUpdate 但這會造成無限循環。 我假設由於 componentDidUpdate 更改了 DOM,然后再次調用 componentDidUpdate 。
componentDidUpdate(prevProps) {
this.getData();
console.log('componentDidUpdate');
}
我想過在菜單中添加onClick={this.handleClick}
並更改狀態或傳遞值以指示新的點擊。 但是必須有一種方法可以捕獲來自路由器的更新,而不僅僅是組件的更改。
如果您在
componentDidUpdate
使用setState
,它會更新組件,導致對componentDidUpdate
的調用隨后再次調用setState
導致無限循環。 您應該有條件地調用setState
並確保最終發生違反調用的條件,例如:
componentDidUpdate(previousProps, previousState) {
if (previousProps.data !== this.props.data) {
this.setState({/*....*/})
}
}
我想出的解決方案是在鏈接中添加一個日期戳,並將其與之前的時間戳進行比較。
<Link to={{"/entity", state: { update: + new Date() } }}>Entities</Link>
componentDidUpdate(prevProps, prevState) {
if (prevProps.update !== this.props.update) {
this.setState({ loading: true })
this.getData();
//console.log('Data Updating - ' + this.props.update);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.