[英]How to load new axios data in react component
I've got a navigation menu that correctly loads components with react-router using <Link to={"/entity"}>Entities</Link>
我有一个导航菜单,可以使用
<Link to={"/entity"}>Entities</Link>
正确加载带有 react-router 的组件
The components load data using axios and display it in tables.组件使用 axios 加载数据并将其显示在表格中。 What I'm struggling to accomplish is loading new data when clicking the
<link>
a subsequent time.我正在努力完成的是在随后单击
<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() {
...
}
This works well for loading a single set of data.这适用于加载一组数据。 But if I edit a row and open the list again it will have the originally retrieved.
但是,如果我编辑一行并再次打开列表,它将获得最初检索的内容。 Which is the correct behaviour given that code, but how can I reload that?
给定该代码,哪种行为是正确的,但我如何重新加载它? I've tried componentDidUpdate but that creates an infinite loop.
我试过 componentDidUpdate 但这会造成无限循环。 I'm assuming due to componentDidUpdate changing the DOM which then again calls componentDidUpdate again.
我假设由于 componentDidUpdate 更改了 DOM,然后再次调用 componentDidUpdate 。
componentDidUpdate(prevProps) {
this.getData();
console.log('componentDidUpdate');
}
I thought about doing something like adding onClick={this.handleClick}
to the menus and changing states or passing values to indicate a new click.我想过在菜单中添加
onClick={this.handleClick}
并更改状态或传递值以指示新的点击。 But there must be a way to catch an update from router and not just a change of the component.但是必须有一种方法可以捕获来自路由器的更新,而不仅仅是组件的更改。
If you use
setState
insidecomponentDidUpdate
it updates the component, resulting in a call tocomponentDidUpdate
which subsequently callssetState
again resulting in the infinite loop.如果您在
componentDidUpdate
使用setState
,它会更新组件,导致对componentDidUpdate
的调用随后再次调用setState
导致无限循环。 You should conditionally callsetState
and ensure that the condition violating the call occurs eventually eg:您应该有条件地调用
setState
并确保最终发生违反调用的条件,例如:
componentDidUpdate(previousProps, previousState) {
if (previousProps.data !== this.props.data) {
this.setState({/*....*/})
}
}
The solution I came up with was to add a datestamp to the link and compare that to the previous timestamp.我想出的解决方案是在链接中添加一个日期戳,并将其与之前的时间戳进行比较。
<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.