使用react-router重复使用相同的组件两次

Sim*_*ton 0 javascript reactjs react-router

我有一个叫做反应类MainContainer,它会显示一些内容.它有一个孩子,SidebarContainer列出了一堆链接.我渲染我的主容器,默认情况下,如果URL中没有param值,则使用默认ID 1作为后备加载第一段内容:

var MainContainer = React.createClass({
  getInitialState: function() {
    return {
      selectedContent: this.props.params.slug || 1
  },

  componentWillReceiveProps: function(nextProps, nextState) {
    this.setState({
      selectedContent: this.props.params.slug || 1
    });
  },
}
Run Code Online (Sandbox Code Playgroud)

SidebarContainer组件有一个链接选择器:

<Link to={content.slug}>
  {content.title}
</Link> 
Run Code Online (Sandbox Code Playgroud)

当我点击链接时,浏览器的URL明显改变,但没有其他任何事情发生.当我再次单击时,会呈现正确的内容.但是,当我使用指定的param复制粘贴url时,它会第一次呈现正确的内容.

我的ReactDOM渲染方法有以下react-router配置:

ReactDOM.render((
  <Router>
    <Route path="/" component={MainContainer}/>
    <Route path="/content/:slug" component={MainContainer}/>
  </Router>
), document.getElementById('react-app'));
Run Code Online (Sandbox Code Playgroud)

我是否componentWillReceiveProps错误地使用了生命周期方法?

Thi*_*ami 5

在里面componentWillReceiveProps,你不应该使用nextProps而不是this.props吗?

this.setState({
      selectedContent: nextProps.params.slug || 1
});
Run Code Online (Sandbox Code Playgroud)