【发布时间】:2023-03-18 10:19:01
【问题描述】:
不久前我问了一个问题,得到了一个对我有很大帮助的答案,但现在我又被难住了。我对 React 有点陌生,所以仍然学习一些技巧和窍门。我有一个页面,其中包含一个完整的表格,内容是根据年份从 API 中获取的。在侧边栏中,我列出了可能的年份。我最初被卡住了,因为我只使用了 ComponentDidMount,但是在单击链接时我需要更新功能。我现在遇到的问题是我需要按两次链接才能更新内容。我在浏览器中可以看到路由发生了变化,但内容没有变化。
我尝试在 Google 上搜索,但找不到任何东西。还尝试使用 React Router 的 this.props.history.push(),因为 API 基于 this.props.match.params.yearId 和 this.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