【问题标题】:Router and Provider inheritance路由器和提供者继承
【发布时间】:2017-04-25 00:11:43
【问题描述】:
我正在学习 React,并希望将 Redux 与 React Router 一起使用。
Provider是Router内部还是相反?什么会更好:
<Provider store={store}>
<Browser>
// routes
</Browser>
</Provder>
或
<Browser>
<Provider store={store}>
// routes
</Provder>
</Browser>
乍一看,我可以同时使用这两种方式。我错过了什么吗?
【问题讨论】:
标签:
javascript
reactjs
redux
react-router
【解决方案1】:
这取决于您是否要将路由状态与您的商店同步。例如,如果你使用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')
)