【问题标题】:React is re rendering the navigation bar all timeReact 一直在重新渲染导航栏
【发布时间】:2018-07-18 05:53:25
【问题描述】:

首先我认为这是一个身份验证问题,正如我一周前在另一篇文章中所说的那样,但现在我尝试做一个简单的导航栏,上面没有任何复杂的代码

class App extends Component {


render() {
return (
      <div>
      <Navigation/>
      <BrowserRouter/>
      <Route exact path= '/' component={Home}/>
      <Route exact path= '/Account' component={Account}/>
      <Route exact path= '/Users' component={Users}/>
      <BrowserRouter/>
      </div>

);
    }
}

导出默认应用;

const Navigation = () =>

<NavigationNonAuth/>


const NavigationNonAuth = () =>

<Navbar inverse collapseOnSelect>
 <Navbar.Header>
  <Navbar.Brand>
    <a href='/'>Refactoring</a>
  </Navbar.Brand>
 <Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
 <Nav pullRight>
  <NavItem eventKey={1} href='/Account'>
    Account
  </NavItem>
  <NavItem eventKey={2} href='/Users'>
   Users
  </NavItem>
 </Nav>
 </Navbar.Collapse>
 </Navbar>
 export default Navigation;

每次我点击导航器、/、/Account 或 /Users 的任何链接时,导航栏都会再次呈现,它不应该

我在 index.js 上使用这个路由

ReactDOM.render((
<BrowserRouter>
<App />
</BrowserRouter>
), document.getElementById('root'));

为什么每次点击导航href链接后都会渲染导航栏?

【问题讨论】:

  • 嗨,大概看this
  • 似乎问题出在 React 引导程序上,我仍然没有设法修复它,但我可以确认导航在没有 React 引导程序的情况下工作。

标签: javascript reactjs


【解决方案1】:

看上面有几个问题,首先你使用了两次&lt;BrowserHistory/&gt;,这是一个反模式。您只需要将&lt;BrowserHistory/&gt; 放在应用程序的顶层即可。

其次,&lt;BrowserHistory/&gt; 是一个 HOC,它将道具附加到您的 &lt;App/&gt; 组件,例如historylocation & match。因为您的 &lt;App/&gt;React.Component 而不是 React.PureComponent 每次这些道具之一更改时,您的 &lt;App /&gt; 被重新渲染,再次呈现您 &lt;Navigation/&gt;

historylocationmatch 会随着路线的变化而变化。

解决方案

  1. 去掉下方的&lt;BrowserHistory /&gt;就不需要了
  2. &lt;App /&gt; 组件更改为React.PureComponent
  3. history 属性传递给&lt;Navigation history={this.props.history}/&gt; 组件
  4. 将您的 &lt;NavItem href='/Users' /&gt; 更改为使用历史记录的 onClick 事件,例如&lt;NavItem onClick={() =&gt; this.props.history.push('/Users')} /&gt;

终于阅读React.PureComponent

https://reactjs.org/docs/react-api.html#reactpurecomponent

【讨论】:

  • 我将 BrowserRouter 更改为 Switch on App.js 并将 React.Component 更改为 React.PureComponent ,但我仍然遇到同样的问题。
  • 是公共组件还是您自己实现的?是否使用“history.push()”?或者它只是一个带有 href 的普通 选项卡?
  • 刚刚在我的回答中添加了 2 个新步骤,React-Bootstrap 不知道 react-router,目前只是在进行标准导航,例如重新加载整个页面。您必须在您的情况下使用 history.push 以编程方式更改路线。 (github.com/ReactTraining/react-router/blob/master/packages/…)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
  • 2016-08-09
  • 1970-01-01
  • 2022-11-23
  • 1970-01-01
  • 2016-07-06
  • 2020-09-09
相关资源
最近更新 更多