DbT*_*ain 5 javascript reactjs react-router
简而言之:我想在 URL 中显示 slug 而不是 Id,最好的方法是什么?
到目前为止,在我的 app.js 组件中,我以这种方式使用 React-router:
<Router history={browserHistory}>
<Route path="/" component={Main}>
<IndexRoute component={Home}></IndexRoute>
<Route path="/profile/:slug" component={Split}></Route>
</Route>
</Router>
Run Code Online (Sandbox Code Playgroud)
然后在我的配置文件组件中,我使用 Link 通过 slug 转到该特定配置文件:
<Link to={'/profile/' + username.slug}>{username}</Link>
Run Code Online (Sandbox Code Playgroud)
我正在考虑在我的轮廓减速器或其他东西中将它们组合在一起?
任何提示都会非常有帮助!
我发现这样做的最好方法是在您的状态中有两个对象,一个是由用户 ID 键控的用户,另一个是由 slug 键控的 slug-id 查找。假设您的用户如下所示:
{
_id: 1234
username: 'Mary Poppins',
slug: 'mary-poppins',
likes: [ 'umbrellas' ]
}
Run Code Online (Sandbox Code Playgroud)
那么您的状态将如下所示:
{
users: {
1234: {
username: 'Mary Poppins',
slug: 'mary-poppins',
likes: ['umbrellas']
}
},
slugs: {
'mary-poppins': 1234
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当您渲染Link组件时,您可以使用:
<Link to=`/profile/${user.slug}`>{user.username}</Link>
Run Code Online (Sandbox Code Playgroud)
并且要在有 slug 时选择用户,您将有一个选择器,例如:
const user = ( slug ) => ( state ) => state.users[state.slugs[slug]];
Run Code Online (Sandbox Code Playgroud)
我会按照您设置路线的方式来完成此操作,然后当您使用 redux 时(因为您说您在编辑之前),我将使用mapStateToProps过滤器,或者您将详细信息作为道具传递。
例如:
const mapStateToProps = (state, ownProps) => {
user: state.users.items.filter(user => user.slug === ownProps.params.slug),
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14368 次 |
| 最近记录: |