【发布时间】:2020-01-06 03:49:24
【问题描述】:
我正在尝试使用基于年份的 API 从我的数据库中提取的一些信息填充一个表。我正在使用 React Router,并希望在我的侧边栏中保留指向不同年份的链接,但动态更改作为此页面主要焦点的表格。
我可以让表格在第一年(2019 年,因为这是默认链接)呈现,但前提是它在 <Switch> 之外。这也导致了链接改变时不改变的问题。
class YearlyTable extends React.Component {
state = {
yearlyTable: [],
isLoading: false,
}
componentDidMount() {
this.setState({ isLoading: true });
axios.get(
`http://localhost/yearTable/${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() {
// isLoading component
// Check what API returns
console.log(this.state.yearlyBonds);
return (
// Removed for simplicity
// This returns a table
{this.state.yearlyTable && <ListTable title={this.state.yearlyTable.Title} data={this.state.yearlyTable.Bonds} />}
// This does not
<Switch>
<Route exact path={`/yearly_table/${this.props.match.params.yearId}${this.props.location.search}`} render={() => this.state.yearlyTable && <ListTable title={this.state.yearlyTable.Title} data={this.state.yearlyTable} />} />
</Switch>
// Sidebar removed for simplicity
);
}
}
export default withRouter(YearlyTable);
我想要实现的结果是它呈现第一个表格,但是当您按下其中一个链接时,它会使用新内容更改表格。
【问题讨论】:
标签: json reactjs typescript axios api-design