react中react-redux和react-router4.*的合营运用

在一个react的项目中,现在来讲项目过大,数据交互多的情况下挑选运用reduxrouter是很罕见的。下面我就用代码的展示情势,来举例:

我们晓得在react-redux的实践中,最外层就是render函数的运用:

import React from 'react';
import {render} from 'react-dom';
import App from './App';
//这里运用render衬着
render(
  <App/>,
  document.getElementById('root')
);

当我们运用redux的时刻,就会先建立一个store,然后运用react-redux供应的Provider作为父组件包裹App:

render(
  <Provider  store={store}>
    <App/>
  </Provider>,
  document.getElementById('root')
);

当搭配router后,这里依然不须要要转变的。我们只须要将router的设置,放入App内里的须要的组件内里:
routerMap.js:

import React,{Component} from 'react';
import {
  BrowserRouter as Router,
  Route,
  Switch
} from 'react-router-dom';
import Home from '../containers/Home';
import User from '../containers/User';
import Search from '../containers/Search';
import Detail from '../containers/Detail';
import City from '../containers/City';
import NotFound from '../containers/404Page';
class App extends Component{
  constructor(props, context){
    super(props, context);
    this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate;
  }
  render(){
    return (
      <Router>
        <div>
          {/**
           * 这里能够大众的款式,比方 头部, 尾部, 等.
           */}
           header
          {/*连系Switch组件能够婚配到都婚配不到的路劲,404等...*/}
          <Switch>
            <Route path='/' exact component={Home}/>
            <Route path='/user'  component={User}/>
            <Route path='/search'  component={Search}/>
            <Route path='/detail'  component={Detail}/>
            <Route path='/city'  component={City}/>
            <Route component={NotFound}/>
          </Switch>
          footer
        </div>
      </Router>
    );
  }
}
export default App;

这时刻后,在最外层:

import React from 'react';
import {render} from 'react-dom';
import App from './routerMap';
//这里运用render衬着
render(
  <Provider  store={store}>
    <App/>
  </Provider>,
  document.getElementById('root')
);

实在末了router和redux的运用是互不影响的,一切正常运用就好。

    原文作者:zachrey
    原文地址: https://segmentfault.com/a/1190000009621052
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞