【问题标题】:How to dynamically update content based on route?如何根据路由动态更新内容?
【发布时间】:2023-03-18 10:19:01
【问题描述】:

不久前我问了一个问题,得到了一个对我有很大帮助的答案,但现在我又被难住了。我对 React 有点陌生,所以仍然学习一些技巧和窍门。我有一个页面,其中包含一个完整的表格,内容是根据年份从 API 中获取的。在侧边栏中,我列出了可能的年份。我最初被卡住了,因为我只使用了 ComponentDidMount,但是在单击链接时我需要更新功能。我现在遇到的问题是我需要按两次链接才能更新内容。我在浏览器中可以看到路由发生了变化,但内容没有变化。

我尝试在 Google 上搜索,但找不到任何东西。还尝试使用 React Router 的 this.props.history.push(),因为 API 基于 this.props.match.params.yearIdthis.props.location.search,它们等于 Year?year=2019(或点击的年份)。

class YearlyTable extends React.Component {
    state = {
        yearlyTable: [],
        isLoading: false,
    }

    componentDidMount() {
        this.setState({ isLoading: true });
        axios.get(
            `http://localhost/YearlyTable/${this.props.match.params.yearId}${this.props.location.search}`,
            { withCredentials: true }
        ).then(res => {
            const yearlyTable = res.data;
            this.setState({ yearlyTable, isLoading: false });
        }).catch((error) => {
            console.log(error);
        });
    }

    updateData(){
        this.setState({ isLoading: true });
        axios.get(
           `http://localhost/YearlyTable/${this.props.match.params.yearId}${this.props.location.search}`,
           { withCredentials: true }
       ).then(res => {
           const yearlyTable = res.data;
           this.setState({ yearlyTable, isLoading: false });
       }).catch((error) => {
           console.log(error);
       });
    }

    render() {
        if (this.state.isLoading) {
            return (
                <Box style={{textAlign: 'center'}}>
                    <CircularProgress color="primary" />
                </Box>
            );
        }

        // Check what API returns
        console.log(this.state.yearlyTable);

        return (
            // Removed for simplicity
            {this.state.yearlyTable && <ListTable title={this.state.yearlyTable.Title} data={this.state.yearlyTable} />}

            // Removed for simplicity (Sidebar)
            // Example of link(MaterialUI, with RouterLink as React-Router-Dom's Link)
            <Link component={RouterLink} to={'/YearlyTable/Year?year=2018'} onClick={this.updateData.bind(this)}>2018</Link>
        );
    }
}
export default withRouter(YearlyTable);

期望的结果是动态更新信息,而不必按两次按钮,因为这是一种糟糕的用户体验。

【问题讨论】:

    标签: reactjs typescript react-router axios api-design


    【解决方案1】:

    使用componentDidUpdate生命周期方法

    componentDidUpdate(prevProps, prevState) {
        if (prevProps.location.search != this.props.location.search && this.state.isLoading != true) {
            this.setState({ isLoading: true });
            axios.get(
                `http://localhost/YearlyTable/${this.props.match.params.yearId}${this.props.location.search}`,
                { withCredentials: true }
            ).then(res => {
                const yearlyTable = res.data;
                this.setState({ yearlyTable, isLoading: false });
            }).catch((error) => {
                console.log(error);
            });
        }
    }
    

    【讨论】:

    • 效果很好,只需将this.props.match.params.yearId 更改为this.props.location.search,因为这是API 工作的参数。非常感谢,现在一直在挠头。没有听说过 ComponentDidUpdate
    • 没问题,componentDidUpdate 生命周期方法将在每次特定组件的 props 或 state 发生变化时被调用。你可以在这里阅读更多。 reactjs.org/docs/react-component.html#componentdidupdate
    猜你喜欢
    • 2022-01-18
    • 2019-09-19
    • 2022-09-28
    • 1970-01-01
    • 2015-08-07
    • 1970-01-01
    • 2021-10-30
    • 2015-06-23
    • 1970-01-01
    相关资源
    最近更新 更多