0
在V4.x上更新React Router V2.x後,所有路由都轉到主頁面。從React路由器V2.x轉換到V4.x
這裏是2.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>
}
});
如何解決這個問題?
是的,這是我使用的代碼,添加確切的不起作用,'/ results'路徑也轉到主頁面。 –
既然我們在這,使用BrowserRouter傳遞的歷史不會被反正使用,它應該在控制檯中打印一條警告。無論如何,我會刪除它,因爲它什麼都不做。或者使用路由器,因爲它是允許您提供自定義歷史記錄的路由器。 另外,我總是用括號括住我的jsx,當它是多行時,也許只是試試以防萬一,我們永遠不知道! –
此外,路由器沒有組件道具,所以只是將其刪除,這可能會導致您的問題,因爲App組件也是由您的withAppLayout HOC返回的。 –