【发布时间】:2021-08-07 20:39:22
【问题描述】:
我正在使用 React Router 路由到不同的路由,如下所示:
<Router>
<Switch>
<Route path="/teams/:teamName/matches" >
<MatchPage/>
</Route>
<Route path="/teams/:teamName" >
<TeamPage/>
</Route>
</Switch>
</Router>
现在在我的 TeamPage 组件中,我使用 async 调用 API,然后在渲染方法中调用另一个名为 MatchDetailCard 的组件
class TeamPage extends Component {
constructor(props) {
console.log('const called')
super(props)
this.state = {
team: [],
teamName:null
}
}
async componentDidMount() {
console.log(this.props.match.params.teamName);
const teamName = this.props.match.params.teamName;
const response = await fetch(`http://localhost:8080/team/${teamName}`);
const json = await response.json();
console.log(json);
this.setState({team:json, teamName: teamName});
}
componentDidUpdate () {
console.log('updated')
}
render() {
if (!this.state.team || !this.state.team.teamName) {
return <h1>Team not found</h1>;
}
return (
<div className="TeamPage">
<div className="match-detail-section">
<h3>Latest Matches</h3>
<MatchDetailCard teamName={this.state.team.teamName} match={this.state.team.matches[0]}/>
</div>
</div>
);
}
}
export default withRouter(TeamPage);
在MatchDetailCard 组件中,我创建了一个路由器Link 到相同的TeamPage 组件,这一次将有一个不同的teamName,如下所示:
const MatchDetailCard = (props) => {
if (!props.match) return null;
const otherTeam = props.match.team1 === props.teamName ? props.match.team2 : props.match.team1;
const otherTeamRoute = `/teams/${otherTeam}`;
const isMatchWon = props.teamName === props.match.matchWinner;
return (
<div className={isMatchWon ? 'MatchDetailCard won-card' : 'MatchDetailCard lost-card'}>
<div className="">
<span className="vs">vs</span><h1><Link to={otherTeamRoute}>{otherTeam}</Link></h1>
</div>
</div>
);
}
export {MatchDetailCard};
我面临的问题是单击/team/teamName 的链接仅路由TeamPage 组件没有安装,而只是获得更新。
我希望调用componentDidMount 挂钩,以便在这种情况下再次调用 API。
我的逻辑有什么问题?
【问题讨论】:
-
见stackoverflow.com/a/50932396/6715484 将你的componentDidMount逻辑分离成一个单独的函数,并像那里描述的那样使用它
标签: reactjs react-router