React Router Link:更改单个参数

时间:2016-06-23 18:38:51

标签: reactjs react-router

我的路线如下:

<Provider store={store}>
    <Router history={browserHistory}>
      <Route path={'/'} component={App}>
        <IndexRoute component={MapContainer} />
        <Route path={'/about'} component={About} />
        <Route path={'/resources'} component={Resources} />
        <Route path={'/:year'} component={MapContainer} />
        <Route path={'/:year/:region'} component={MapContainer} />
      </Route>
    </Router>
  </Provider>

/:year/:year/:region之后,路线列表会显着增长(例如/:year/:region/:country)。

我有一个更改年份的链接,但我只想更改year参数,以便/2013/northern-africa/morocco上的链接可以链接到/2006/northern-africa/morocco。基本上,我希望它在year之后保留所有参数。

我有这个:

const years = ['2013', '2006', '2002', '1998', '1995'];
const yearLinks = years.map(y => (<li className={y === this.props.params.year ? 'current' : null}>
  <Link to={`/${y}/${this.props.params.region}`}>{y}</Link>
</li>));

这基本上是填补

<ul>
  {yearLinks}
</ul>

这仅适用于地区,我不想做for param, value in this.props.params之类的事情,然后只需附加所有参数。似乎react-router应该能够解决这个问题。此外,参数的顺序不太可能按照我需要它们制作有效URL的顺序返回。

1 个答案:

答案 0 :(得分:2)

我写了JsFiddle that demonstrates changing a single parameter。它使用Navigation router而不是React路由器,但我希望您对此持开放态度。您可以看到使用路由器的RefreshLink组件构建超链接。它具有includeCurrentData属性,当设置为true时,保留当前的URL数据。因此,要保留region参数但更改年份,请传递新年并将includeCurrentData设置为true。如果URL中有国家/地区参数,它也会保留该参数。如果您对代码有任何疑问,请告诉我们。

var {StateNavigator} = Navigation; 
var {RefreshLink} = NavigationReact; 

var Map = ({year, region, stateNavigator}) => {
  var regions = ['northern-africa', 'southern-africa'];
  var years = [2013, 2006, 2002, 1998, 1995];
  return (
    <div>
      {regions.map((region) => 
        <RefreshLink
            navigationData={{region: region}}
            includeCurrentData={true}
            stateNavigator={stateNavigator}>
            {region}
        </RefreshLink>
      )}
      <br/>
      {years.map((year) => 
        <RefreshLink
            navigationData={{year: year}}
            includeCurrentData={true}
            stateNavigator={stateNavigator}>
            {year}
        </RefreshLink>
      )}
      <div>year: {year}</div>
      <div>region: {region}</div>
    </div>
  );
};

var stateNavigator = new StateNavigator([
  {key:'map', route:'{year?}/{region?}', defaults: {year: 2016 }}
]);

stateNavigator.states.map.navigated = (data) => {
  ReactDOM.render(
    <Map year={data.year} region={data.region} stateNavigator={stateNavigator} />,
    document.getElementById('content')
  );
}

stateNavigator.start();