如何从使用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/[email protected]/dist/react.min.js"></script>
<script src="https://unpkg.com/[email protected]/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版本,尽管它不起作用(return语句后无法访问的代码)。
最佳答案
通过更改以下内容,我可以使用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 } />
其他所有内容都应该相同。
如果有人碰到
The prop history is marked as required in Router, but its value is undefined.
这是因为
browserHistory
在react-router中不再可用,请参阅post以使用历史包。有关的
关于javascript - 从React Router 3.x移至4.x,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41699003/