IndexRedirect仅在尚未定义段时?

时间:2016-05-05 13:29:02

标签: reactjs react-router

我有这个简单的应用程序:

let nextParent = LinkingObjects(fromType: Flight.self, property: "nextFlight")
let previousParent = LinkingObjects(fromType: Flight.self, property: "previousFlight")
var parent: Flight? { return nextParent.first ?? previousParent.first }

当我在// index.js import React from 'react' import { render } from 'react-dom' import { Router, Route, IndexRedirect, browserHistory } from 'react-router' import A from './a' import B from './b' render(( <Router history={browserHistory}> <Route path='/foo' component={A}> <IndexRedirect to='1' /> <Route path=':bar' component={B} /> </Route> </Router> ), document.getElementById('root')) 时,如果点击指向/foo/3的链接,我会被重定向到/foo/

是否有一种简单的方法可以将/foo/1重定向到已使用的IndexRedirect而不是默认值?

1 个答案:

答案 0 :(得分:0)

您可以使用browserHistory侦听器

browserHistory.listen(function(ev) {
    console.log('listen', ev.pathname.split('/'));
     var pathData = ev.pathname.split('/'); 
});

并将您的<IndexRedirect to='1' />替换为您想要的任何内容 例如:

var defaultIndex = 1
browserHistory.listen(function(ev) {
    console.log('listen', ev.pathname.split('/'));
    var pathData = ev.pathname.split('/');
    defaultIndex = pathData[1]
});
<Router history={browserHistory}>
    <Route path='/foo' component={A}>
        <IndexRedirect to={defaultIndex} />
        <Route path=':bar' component={B} />
    </Route>
</Router>

这适合我。