【问题标题】:Re-using the same component twice with react-router使用 react-router 重复使用相同的组件两次
【发布时间】:2016-09-30 23:01:43
【问题描述】:

我有一个名为 MainContainer 的反应类,它显示一些内容。它有一个孩子SidebarContainer,列出了一堆链接。如果 URL 中没有参数值,我会渲染我的主容器并默认使用默认 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
    });
  },
}

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

<Link to={content.slug}>
  {content.title}
</Link> 

当我点击链接时,浏览器的 URL 明显改变,但没有其他反应。当我再次单击时,会呈现正确的内容。但是,当我复制粘贴带有指定参数的 url 时,它会第一次呈现正确的内容。

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

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

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

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    componentWillReceiveProps里面,不应该用nextProps代替this.props吗?

    this.setState({
          selectedContent: nextProps.params.slug || 1
    });
    

    【讨论】:

    • 是的,这就是我所缺少的 :)
    【解决方案2】:

    在导航后强制更新页面的一种有效方法是根据路由器参数为页面组件分配一个键。这样,如果您使用不同的参数导航到同一页面,react 将卸载前一个并安装新的。

    这个技巧可以让您不必手动重置组件的内部状态,并防止一些错误,因为上一页的状态过时。

    【讨论】:

      【解决方案3】:

      使用内部状态很奇怪,而您可以在组件内部的任何位置直接访问 this.props.slug。

      顺便问一下,您的路由器可能缺少某些东西吗?浏览器历史?

      import {browserHistory} from 'react-router'
      
      <Router history={browserHistory}>
          ...
      </Router>
      

      【讨论】:

        猜你喜欢
        • 2016-08-17
        • 2019-08-12
        • 1970-01-01
        • 2017-05-17
        • 2017-12-29
        • 1970-01-01
        • 2014-12-21
        • 2017-10-15
        • 2019-08-02
        相关资源
        最近更新 更多