2017-02-14 67 views
3

我想我的反應路由器有一些問題。我怎樣才能防止反應路由器重新渲染先前呈現的頁面?如何防止反應路由器重新呈現以前呈現的頁面?

我有路由器這樣的代碼:

class App extends React.Component { 
 
    render() { 
 
    return (
 
     <div> 
 
      <NavBar/> 
 
      {this.props.children} 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    (
 
     <Router history={hashHistory}> 
 
      <Route path="/" component={App}> 
 
       <IndexRoute component={Gateway} /> 
 
       <Route path="home" component={Gateway} /> 
 
       <Route path="categories" component={Categories} /> 
 
      </Route> 
 
     </Router> 
 
    ), document.getElementById('my-app') 
 
);

當我第一次訪問該頁面,它擊中指數,Gateway組件得到了呈現。然後我點擊「類別」鏈接,類別組件得到渲染。然後,當我再次點擊「home」鏈接時,組件網關被重新渲染。它的狀態得到了RESET。這真是令人沮喪,因爲我無法弄清楚爲什麼它的狀態得到重置。

有沒有解決方案?

+0

如果您沒有使用Redux等任何狀態管理,那麼您必須查找正確的方式來使用React共享路由之間的狀態。看看這個帖子中的答案:http://stackoverflow.com/questions/41108701/react-router-share-state-between-routes-without-redux或谷歌的東西,如「反應路由器之間的路由器共享狀態」 – Jayce444

回答

1

如果您想要保存任何狀態,則應將其存儲在某個位置,例如組件的狀態(如果使用了redux,則爲redux狀態)。

在反應中,您可以在組件中定義函數shouldComponentUpdate()以強制React不重新呈現您的DOM。但是在反應路由器的情況下,第一條路由的DOM被破壞(不僅僅是隱藏),因此應該重新渲染。