react中react-redux和react-router4.*的配合使用


在一個react的項目中,目前來講項目過大,數據交互多的狀況下選擇使用reduxrouter是很常見的。下面我就用代碼的展示形式,來舉例:react

咱們知道在react-redux的實踐中,最外層就是render函數的使用:redux

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:react-router

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

當搭配router後,這裏仍然不須要要改變的。咱們只須要將router的配置,放入App裏面的須要的組件裏面:
routerMap.js:dom

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;

這時候後,在最外層:ide

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的使用是互不影響的,一切正常使用就好。函數

相關文章
相關標籤/搜索