从React Router V2.x转换为V4.x.

时间:2017-07-17 19:31:10

标签: reactjs ecmascript-6 react-router

在V4.x上更新React Router V2.x后,所有路由都会转到主页面。

以下是V2.x上的路线:

import {Router, Route, hashHistory } from 'react-router'

const routes = <Route component={App}>
  <Route path="/results" component={Results} />
  <Route path="/" component={Voting} />
</Route>;

ReactDOM.render(
  <Router history={hashHistory}>{routes}</Router>,
  document.getElementById('app')
);

这些是V4.x上的路线:

index.jsx文件:

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import App from './components/App';
import Voting from './components/Voting';
import Results from './components/Results';

const withAppLayout = Component => props => <App><Component {...props} /></App>

const routes = <Switch>
    <Route exact path="/" component={withAppLayout(Voting)} />
    <Route path="/results" component={withAppLayout(Results)} />
</Switch>;

ReactDOM.render(
        <Router component={App}>
            {routes}
        </Router>,
        document.getElementById('app')
        );

App.jsx文件:

import React from 'react';
import {List} from 'immutable';

const pair = List.of('Trainspotting', '28 Days Later');

export default React.createClass({
    render: function () {
        console.log(this.props.children);
        return React.cloneElement(this.props.children, {pair: pair});
    }
});

Voting.jsx文件:

import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import Winner from './Winner';
import Vote from './Vote';

export default React.createClass({
    mixins: [PureRenderMixin],
    render: function () {
        return <div>
            {this.props.winner ?
                            <Winner ref="winner" winner={this.props.winner} /> :
                            <Vote {...this.props} />
            }
        </div>;
    }
});

Results.jsx文件:

import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';

export default React.createClass({
    mixins: [PureRenderMixin],
    render: function () {
        return <div>Hello from results!</div>
    }
});

如何解决此错误?

1 个答案:

答案 0 :(得分:1)

有一件事是使用:

<Route exact path="/" component={withAppLayout(Voting)} />

确切的将确保只有那个确切的路径匹配。但是如果你有其他人之后的路径=“/”,那么其他人应该首先匹配。这是你正在使用的真实代码吗?

编辑:查看下面的完整版本。

import {BrowserRouter, Route, Switch} from 'react-router-dom'

ReactDOM.render(
    <BrowserRouter>
        <Switch>
            <Route exact path="/" component={Voting} />
            <Route path="/results" component={Results} />
        </Switch>
    </BrowserRouter>,
    document.getElementById('app')
);

然后,如果能够解决问题,您可以将Switch部分移动到App Component中。此外,如果要使用哈希历史记录,则需要使用基本上使用哈希历史记录初始化路由器的HashRouter。