[英]Access redux store from redux-simple-router children
我試圖弄清楚如何從路由內訪問redux存儲,以便我可以從路由內調度操作。
這是我的頂級組件的外觀:
class App extends Component {
render() {
return (
<div>
{ children }
</div>
);
}
}
我的redux-simple-router代碼如下所示:
render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={ Home } />
<Route path="/example" component={ ExampleRoute } />
</Route>
</Router>
</Provider>,
rootElement
)
如果我從ExampleRoute組件中轉儲道具,則無權訪問商店。 任何幫助表示贊賞!
您應該使用connect
from react-redux
從存儲中獲取dispatch
和當前狀態。 此處的redux文檔中對此進行了概述: http ://rackt.org/redux/docs/basics/UsageWithReact.html
這是您的Example
組件:
//...
import { connect } from 'react-redux'
//...
export class Example extends Component {
render () {
const { dispatch, thingName } = this.props
return (
<button onClick={ () => {
dispatch(myAwesomeActionCreator())
}}>{ thingName }</button>
);
}
}
export default connect(state => state)(Example)
在react-redux
文檔中可以找到一些如何使用connect
好例子: https : //github.com/rackt/react-redux/blob/master/docs/api.md#examples
我能夠使用“ Monkeypatch”中間件來工作,但是必須有一種更好的方法。
首先,我創建了一個函數來對children變量進行猴子補丁。 此函數將子級,調度和存儲作為參數,並返回具有存儲和調度鍵的更新的子變量:
function routeStoreMiddleware (children, dispatch, store) {
return {
...children,
props: {
...children.props,
dispatch: dispatch,
store: store
}
}
}
然后,我簡單地更新了已經可以訪問調度和存儲以使用中間件功能的組件:
class App extends Component {
render() {
return (
<div>
{ routeStoreMiddleware(children, dispatch, store) }
</div>
);
}
}
由於命名不佳的routeStoreMiddleware函數僅返回更新的子對象,因此它仍然有效。
現在,我可以在ExampleRoute組件中調度事件並顯示數據。
從'react'導入React,{組件}; 從'../actions.js'導入{myAwesomeActionCreator}
export class Example extends Component {
render () {
const { dispatch, store } = this.props
return (
<button onClick={ () => {
dispatch(myAwesomeActionCreator())
}}>{ store.thingName }</button>
);
}
}
好極了!
請注意:我已經在這里閱讀了很多有關如何在Redux中正確制作中間件的信息,但是我還沒有時間充分了解它。 有比我在這里做的更好的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.