繁体   English   中英

如何在反应组件中加载新的 axios 数据

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM