路由器和提供程序继承

时间:2017-04-25 00:11:43

标签: javascript reactjs redux react-router

我正在学习React,并希望将Redux与React Router一起使用。 路由器内的提供商或对面是否重要?什么会更好:

<Provider store={store}>
  <Browser>
   // routes
  </Browser>
</Provder>

<Browser>    
  <Provider store={store}>
   // routes
  </Provder>
</Browser>

初看起来我可以使用这两种方式。我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

这取决于您是否要将路由状态与商店同步。例如,如果您使用的是react-router-redux,则需要先设置Provider,然后设置Router

  

来自文档:

import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import { syncHistoryWithStore, routerReducer } from 'react-router-redux'

import reducers from '<project-path>/reducers'

// Add the reducer to your store on the `routing` key
const store = createStore(
  combineReducers({
    ...reducers,
    routing: routerReducer
  })
)

// Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store)

ReactDOM.render(
  <Provider store={store}>
    { /* Tell the Router to use our enhanced history */ }
    <Router history={history}>
      <Route path="/" component={App}>
        <Route path="foo" component={Foo}/>
        <Route path="bar" component={Bar}/>
      </Route>
    </Router>
  </Provider>,
  document.getElementById('mount')
)