在Redux 应用中使用路由功能,可以搭配使用 React Router 来实现。 Redux 和 React Router 将分别成为数据和 URL 的事实来源(the source of truth)。 在大多数情况下, 最好将他们分开,除非需要时光旅行和回放 action 来触发 URL 改变。
1、需要从 React Router 中导入
import { Router, Route, browserHistory } from 'react-router';
在 React 应用中,通常需要会用
const Root = () => (
);
另外,在 Redux 应用中,仍将使用
然后,开发者从 React Redux 导入
import { Provider } from 'react-redux';
开发者将用
const Root = ({ store }) => (
);
2、渲染组件
现在,如果 URL 匹配到 '/',将会渲染
也可以将 '#' 从 URL 中移除(例如:)。 开发者需要从 React Router 导入 browserHistory 来实现:
import { Router, Route, browserHistory } from 'react-router';
然后将它传给
只要开发者不需要兼容古老的浏览器,比如IE9,你都可以使用 browserHistory。
components/Root.js
import React, { PropTypes } from 'react';
import { Provider } from 'react-redux';
import { Router, Route, browserHistory } from 'react-router';
import App from './App';
const Root = ({ store }) => (
);
Root.propTypes = {
store: PropTypes.object.isRequired,
};
export default Root;