简体   繁体   English

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

[英]Re-using the same component twice with react-router

I have a react class called MainContainer which displays some content. 我有一个名为MainContainer的反应类,它显示一些内容。 It has a child, SidebarContainer that lists a bunch of links. 它有一个子项SidebarContainer ,列出了一系列链接。 I render my main container and by default load the first piece of content using a default ID of 1 as a fallback if there is no param value in the URL: 我呈现了我的主容器,默认情况下,如果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
    });
  },
}

The SidebarContainer component has a Link selector: SidebarContainer组件具有一个链接选择器:

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

When I click on the link, the browser's URL visibly changes, but nothing else happens. 当我单击链接时,浏览器的URL会发生明显变化,但没有其他反应。 When I click again, the correct content renders. 当我再次单击时,将呈现正确的内容。 However, when I copy-paste a url with a specified param, it renders the correct content first time around. 但是,当我复制粘贴具有指定参数的url时,它将在第一时间呈现正确的内容。

My ReactDOM render method has the following react-router config: 我的ReactDOM渲染方法具有以下react-router配置:

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

Am I using the componentWillReceiveProps lifecycle method incorrectly? 我使用了componentWillReceiveProps生命周期方法吗?

Inside componentWillReceiveProps , shouldn't you use nextProps instead of this.props? componentWillReceiveProps内部,是否应该使用nextProps代替this.props?

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

An effective way to force updating a page after navigation, consists of assigning a key to the page component based on the router parameter. 导航后强制更新页面的有效方法包括根据路由器参数为页面组件分配密钥。 This way, if you navigate to the same page with a different parameter, react will unmount the previous one and mount the new one. 这样,如果您使用不同的参数导航到同一页面,则react将卸载前一个页面并安装新页面。

This trick can save you from having to reset the components' internal state manually and prevent some bugs for having a stale state from the previous page. 此技巧可以使您不必手动重置组件的内部状态,并且可以避免上一页中由于过时而导致的某些错误。

It's strange to use internal state, while you can directly access to this.props.slug anywhere inside of your component. 使用内部状态很奇怪,而您可以直接在组件内部的任何位置访问this.props.slug。

By the way, may be there's something missing on your router? 顺便说一句,您的路由器上可能缺少某些东西吗? the browserHistory? browserHistory?

import {browserHistory} from 'react-router'

<Router history={browserHistory}>
    ...
</Router>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM