Abh*_*ash 1 reactjs react-router
我使用 React Router 路由到不同的路由,如下所示:
<Router>
<Switch>
<Route path="/teams/:teamName/matches" >
<MatchPage/>
</Route>
<Route path="/teams/:teamName" >
<TeamPage/>
</Route>
</Switch>
</Router>
Run Code Online (Sandbox Code Playgroud)
现在,在我的TeamPage组件中,我使用调用 API async,然后在渲染方法中调用另一个名为的组件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);
Run Code Online (Sandbox Code Playgroud)
在组件内,我创建了一个指向同一组件的MatchDetailCard路由器,这次将有不同的路由器,如下所示:LinkTeamPageteamName
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};
Run Code Online (Sandbox Code Playgroud)
我面临的问题是,单击/team/teamName仅路由TeamPage组件的链接并未安装,而只是获得更新。
在这种情况下,我想要调用componentDidMounthook 来再次进行 API 调用。
我的逻辑有什么问题吗?
\n\n如果同一个组件在组件树中的同一点用作多个
\n<Route>s 的子组件,React 会将其视为同一组件实例,并且在路由更改之间将保留 component\xe2\x80\x99s 状态。如果这不是\xe2\x80\x99t所需要的,添加到每个路由组件的唯一 key 属性将导致 React 在路由更改时重新创建组件实例。
https://reactrouter.com/web/api/Route
\n您可以将 teamName 添加为组件上的 key prop,这将告诉 React 在键值更改时卸载/挂载组件。
\n<Router>\n <Switch>\n <Route\n path="/teams/:teamName/matches"\n render={({ match }) => {\n return <MatchPage key={match.params.teamName} />;\n }}\n />\n <Route\n path="/teams/:teamName"\n render={({ match }) => {\n return <TeamPage key={match.params.teamName} />;\n }}\n />\n </Switch>\n</Router>\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
1296 次 |
| 最近记录: |