React-Router

react中,Router是一个组件,在任何地方都可以使用。但是为了代码结构的整洁,我们一般把Router做为容器性组件处理。

配置Router

  • 安装

    yarn add react-router react-router-dom history react-router-redux
    //or
    npm i react-router react-router-dom history react-router-redux
    
  • 关联redux

    我们知道一个工程只有一个store,而且由store来管理整个工程的state,所以必须将router交给store来管理。

    import { routerReducer, routerMiddleware } from 'react-router-redux';
    import { createBrowserHistory } from 'history';
    import { applyMiddleware } from 'redux';
    import Reducer from '../reducers/Index';
    
    const history = createBrowserHistory();
    
    createStore(
        combineReducers({
          ...Reducer,
          routing: routerReducer
        }),
        applyMiddleware(routerMiddleware(history), createLogger())
      )
    
    • 加入Router
    import React from 'react';
    import ReduxConfig from '../store/Store';
    import { Provider } from 'react-redux';
    import { Router } from 'react-router'
    
    const { history, store } = ReduxConfig;
    
    export default ({ children }) => <Provider store={store}>
      <Router history={history}>
        {children}
      </Router>
    </Provider>
    
    • Link

      类似a标签,提供一个超链接。

      <Link to={'/home'} >Go Home</Link>
      
    • 跳转到指定页面

      有时候无法在表现性组件中使用Link时,可以使用history来跳转。

      import {push} from 'react-router-redux';
      
      dispatch => {
        dispatch(push('/home'));
      };
      

在线实例

results matching ""

    No results matching ""