2017-04-23 54 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 ..." 
      /> 
     ) 
    } 
}