2017-07-26 73 views
0

當兩個路由使用相同的組件時,如何在路由更改時重新裝載組件?React force在路由更改時重新裝載組件

這是我的代碼。

routes.jsx

<Router history={browserHistory}> 
    <Route path="/" component={Home} /> 
    <Route path="/foo/:fooId" component={Home} /> 
</Router> 

我在Home成分爲fooId一個條件檢查,其相應地呈現JSX。

<Link to="/foo/1234">fooKey</Link> 

目前,上fooKey點擊路線的變化和家庭組成的渲染功能被重新觸發,但不會被再次安裝時。

我經歷了其他的提到componentWillReceiveProps的答案,但我在constructor中有很多配置,我不想將所有配置都移動到componentWillReceiveProps

如果需要更多信息,請發表評論。

+3

強制unmount是React中的反模式。 componentWillReceiveProps是做到這一點的正確方法,然後您的代碼將與其他讀者/貢獻者期望的內容相匹配。 –

+0

同意,沒有好辦法做到這一點,即使有,你也不需要。如果構造函數中有配置或數據需要在實例化後可變,那麼它應該移出構造函數並進入'state'。 – jered

+0

感謝您的建議。如果您可以指示我對組件不應該重新安裝的更多解釋,這將會很有幫助。很明顯,性能會降低,但還有其他原因嗎? –

回答

0

顯然,如果你需要強制重新安裝,你做錯了什麼。一般來說,你應該componentWillReceiveProps反應:

class DumbComponent extends React.Component { 
    constructor(props) { 
    super(props); 

    this.state = this.propsToState(this.props); 
    } 

    componentWillReceiveProps(nextProps) { 
    this.setState(this.propsToState(nextProps)); 
    } 

    propsToState(props) { 
    // place all of your state initialization dependent logic here 
    return { 
     foo: props.foo, 
    }; 
    } 

    render() { 
    return <div>{this.state.foo}</div> 
    } 
} 
+0

這不是處理道具和狀態的方法。你希望任何一塊數據都有一個真實的來源。如果你需要渲染狀態和道具的組合,你可以在需要時執行該邏輯。 –

2

所以你不會要取消安裝,每個查詢字符串的變化時重新安裝你的組件。您的路線改成這樣:

<Router history={browserHistory}> 
    <Route path="/" component={Home} /> 
</Router> 

與陣營路由器提供的withRouter特別包裝你<Home />組件。完成之後,({ match, history, location })將在<Home />組件中可用。在您的componentWillRecieveProps生命週期鉤子中,您可以執行任何需要props.location.search上的查詢字符串以產生所需結果的邏輯。

相關問題