【问题标题】:Best practice for dynamic routing (react router v4) needed?需要动态路由(反应路由器 v4)的最佳实践吗?
【发布时间】:2017-04-23 02:55:19
【问题描述】:

由于 React Router V4 仅推出了一段时间,并且没有关于动态路由的明确文档 [类似于 V3 中的transtionsTo(...)],我觉得对这个问题的简单回答可以让很多人受益。所以我们开始吧。

让我们假设以下理论场景:一个组件有一个 Container,其中包含两个其他组件(SelectionDisplay)。现在在功能方面: Container持有一个状态,可以通过Selection改变,Display根据该状态显示数据。

现在如何去改变 URL 以及通过反应路由器改变状态所触发的状态?

有关更具体的示例,请参阅 (React Router V4 - Page does not rerender on changed Route)。但是,我觉得有必要概括和缩短问题以达到任何目的。

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    感谢 [Tharaka Wijebandara] 这个问题的解决方案是: 让 Container 组件为 Selection 组件提供回调函数,该回调函数必须至少对 Container 执行以下操作:

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

    请在下面找到 Container(称为 Geoselector)组件的示例,将 setLocation 回调传递给 Selection(称为 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 ..."
                />
            )
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-11-30
      • 2017-12-06
      • 2018-07-09
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-16
      • 1970-01-01
      相关资源
      最近更新 更多