如何从使用 https://cdnjs.cloudflare.com/ajax/libs/react-router/4.0.0-2/react-router.min.js
转向使用 https://cdnjs.cloudflare.com/ajax/libs/react-router/3.0.1/ReactRouter.min.js
?
下面使用 3.x 的示例。
HTML
<script src="https://unpkg.com/react@15.4.2/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom@15.4.2/dist/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-router/3.0.1/ReactRouter.min.js"></script>
JS
let { Router, IndexRoute, Redirect, Route, Link, browserHistory } = ReactRouter;
history.replaceState(0,0,'/');
const Main = () =>
<Router history={browserHistory}>
<Route path='/' component={App}>
<IndexRoute component={Home}/>
<Route path='map' component={Map}/>
<Route path='settings' component={Settings}/>
<Redirect from='foo' to='/' />
<Route path='*' component={NotFound}/>
</Route>
</Router>
const App = props =>
<div>
<Navigation>
<Link to='/map'>Map</Link>
<Link to='/settings'>Settings</Link>
<Link to='/foo'>Foo</Link>
</Navigation>
{props.children}
</div>
const Navigation = props => <nav {...props} />
const Home = () => <h1>Home</h1>
const Map = () => <h1>Map</h1>
const Settings = () => <h1>Settings</h1>
const NotFound = (props) => <h1>404 - Not Found</h1>
ReactDOM.render(<Main />, document.body);
查看实际效果:https://jsfiddle.net/developit/nvpr63eg/
如果我迁移到任何 CDN 托管的 4.x 版本,尽管它不起作用(返回语句后无法访问代码)。
最佳答案
我可以通过更改一些内容来使用 redux 配置它:
首先,browserHistory
不再在react-router
上定义。恢复它的一种方法是使用包 history
。
您需要安装(redux 可选):
npm i -S history react-router react-router-redux
不要尝试导入browserHistory
,而是使用:
import { createBrowserHistory } from 'history';
如果你想使用 redux,那么导入它并将其添加到你的组合 reducer 中:
import { routerReducer as routing } from 'react-router-redux';
combineReducers({
home, about,
routing, // new
});
接下来创建 history
对象
// redux
import { syncHistoryWithStore } from 'react-router-redux';
const history = syncHistoryWithStore(createBrowserHistory(), store);
// regular
const history = createBrowserHistory();
然后更改您的路由器以使用新的 history
对象
<Router history={ history } children={ Routes } />
其他一切都应该是相同的。
<小时/>如果有人遇到 Prop 历史记录在路由器中被标记为必需,但其值未定义。
这是因为 browserHistory
在react-router中不再可用,请参阅帖子以使用history包。
相关
关于javascript - 从 React Router 3.x 迁移到 4.x,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41699003/