ReactJS-使用React路由器在URL中使用slug而不是Id

时间:2017-03-07 22:32:13

标签: javascript reactjs react-router

简而言之:我想在网址中显示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>

然后在我的个人资料组件中,我使用链接通过slug转到该特定的配置文件:

<Link to={'/profile/' + username.slug}>{username}</Link>

我在考虑将它们放在我的配置文件缩减器或其他东西中?

任何提示都会非常有用!

2 个答案:

答案 0 :(得分:3)

我发现这样做的最好方法是在你的状态中有两个对象,一个是用户id键入的用户,另一个是slug-id查找,用slug键入。假设您的用户看起来像这样:

zoomable: false,

然后你的州看起来像:

{
    _id: 1234
    username: 'Mary Poppins',
    slug: 'mary-poppins',
    likes: [ 'umbrellas' ]
}

现在,在渲染{ users: { 1234: { username: 'Mary Poppins', slug: 'mary-poppins', likes: ['umbrellas'] } }, slugs: { 'mary-poppins': 1234 } } 组件时,请使用:

Link

要在有slug时选择用户,你会有一个选择器,如:

<Link to=`/profile/${user.slug}`>{user.username}</Link>

答案 1 :(得分:0)

我会按照您设置路线的方式进行操作,然后当您使用redux时(因为您之前说过您是编辑之前)我会使用mapStateToProps进行过滤,但不管您是将细节作为道具传递。

示例

const mapStateToProps = (state, ownProps) => {
  user: state.users.items.filter(user => user.slug === ownProps.params.slug),
}