2017-04-23 93 views
0

隨着React Router V4只出現一段時間,並且沒有關於動態路由的清晰文檔[類似於V3中的transtionsTo(...)],我覺得對這個問題的簡單回答可能會使許多人受益。所以,我們走了。需要動態路由(反應路由器v4)的最佳實踐?

讓我們假設下面的理論情形:一個具有一組分集裝箱,它包括另外兩個組成部分(選擇顯示)。現在在功能方面: 容器保持一個狀態,它可以改變選擇,顯示顯示基於所述狀態的數據。

現在該如何改變URL以及由狀態變化通過反應路由器觸發的狀態?

有關更具體的示例,請參閱(React Router V4 - Page does not rerender on changed Route)。但是,我覺得有必要將問題概括並縮短到任何地方。

回答

0

禮貌爲[Tharaka Wijebandara]解決這個問題是: 具有集裝箱部件提供選擇組分與具有至少做就集裝箱以下回調函數:

props.history.push(Selection coming from Selection);

請看以下集裝箱(稱爲Geoselector)成分的例子,通過定義的setLocation回調下降到選擇(稱爲Geosuggest)組件。

class Geoselector extends Component { 
    constructor (props) { 
     super(props); 
     this.setLocation = this.setLocation.bind(this); 
     //Sets location in case of a reload instead of entering via landing 
     if (!Session.get('selectedLocation')) { 
      let myRe = new RegExp('/location/(.*)'); 
      let locationFromPath = myRe.exec(this.props.location.pathname)[1]; 
      Session.set('selectedLocation',locationFromPath); 
     } 
    } 

    setLocation(value) { 
     const newLocation = value.label; 
     if (Session.get('selectedLocation') != newLocation) { 
      Session.set('selectedLocation',newLocation); 
      Session.set('locationLngLat',value.location); 
      this.props.history.push(`/location/${newLocation}`) 
     }; 
    } 


    render() { 
     return (
      <Geosuggest 
       onSuggestSelect={this.setLocation} 
       types={['(cities)']} 
       placeholder="Please select a location ..." 
      /> 
     ) 
    } 
}