[英]How to make a layout in React Router v4
我已经进行了大量谷歌搜索,但无法解决我遇到的问题...
我正在建立一个社交网络个人资料页面,上面有不同的部分。 我希望核心个人资料信息始终可见,但是单击某些链接(例如“照片”)以更改其他组件。
这是我的代码:
App.js(路线)
class App extends React.Component {
[ ... ]
render() {
return (
<Router>
<Navigation {...props} />
<Switch>
<Route exact path="/u/:id" component={Profile} />
<Route component={NotFound} />
</Switch>
<Footer />
</Router>
);
}
}
配置文件组件(根据用户帐户类型更改呈现的内容):
const renderProfile = (user, id, type) => {
if (type === 'artist') {
return <Route render={() => <ArtistProfilePage id={id} />} />;
} else {
[ ... ]
}
};
const Profile = ({ loading, user, id, type }) => (<div>
{ !loading && renderProfile(user, id, type) }
</div>);
ArtistProfilePage(这是我要始终显示某些组件但如果URL更改则加载不同组件的页面:
class ArtistProfilePageNew extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="ArtistProfilePage">
<ArtistInfo />
<Link to="/">Artist Media</Link>
<Link to="lineup">Line-up</Link>
<Link to="gigs">Gigs</Link>
<Switch>
<Route path="/" render={() => <ArtistMedia />} /> // this works
<Route path="/lineup" render={() => <ArtistLineup />} /> // this doesn't
</Switch>
</div>
);
}
}
我想要实现的是,当url为u/:id
且用户类型为'artist'时,显示ArtistProfilePage
组件。 这工作
默认情况下,我希望ArtistProfilePage呈现<ArtistMedia />
组件,该组件也可以正常工作
我的问题是,当用户点击链接的lineup
,因此URL变为u/:id/lineup
,应用程序显示了404页,而不是渲染<ArtistLineup />
下部分<ArtistInfo />
和链接。
我究竟做错了什么? 谢谢
在ArtistProfilePageNew
中创建路由/ lineup时,需要在其之前附加上一个URL。 因此,您的组件将变为:
class ArtistProfilePageNew extends React.Component {
constructor(props) {
super(props);
}
render() {
const { match } = this.props;
return (
<div className="ArtistProfilePage">
<ArtistInfo />
<Link to={`${match.url}/`}>Artist Media</Link>
<Link to={`${match.url}/lineup`}>Line-up</Link>
<Link to={`${match.url}/gigs`}>Gigs</Link>
<Switch>
<Route path={`${match.url}/`} component={ArtistMedia} />
<Route path={`${match.url}/lineup`} component={ArtistLineup} />
</Switch>
</div>
);
}
}
另外,我会将您的个人资料组件更改为此:
const renderProfile = (user, id, type, match) => {
if (type === 'artist') {
return <ArtistProfilePage id={id} match={match} />;
} else {
[ ... ]
}
};
const Profile = ({ loading, user, id, type, match }) => (<div>
{ !loading && renderProfile(user, id, type, match) }
</div>);
由于Profile组件是通过Route渲染的,因此它应该自动获取注入的match参数。 如果没有,那么您需要使用react-router
包中的withRouter
包装您的ArtistProfilePageNew。
我的解决方案未经测试,但是应该可以使您了解问题所在。
希望能帮助到你!
编辑:您需要从父路由中删除确切的参数,因此您的应用将变为:
class App extends React.Component {
render() {
return (
<Router>
<Navigation {...props} />
<Switch>
<Route path="/u/:id" component={Profile} />
<Route component={NotFound} />
</Switch>
<Footer />
</Router>
);
}
}
CodePen上的Wokring示例: https ://codepen.io/anon/pen/eeMMBd
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.