从redux-simple-router儿童访问redux商店
我试图弄清楚如何从路由内部访问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组件内部转储道具,我无法访问商店。 任何帮助感激!
您应该使用react-redux
进行connect
以从商店获取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)
有关如何使用connect
一些很好的例子可以在react-redux
文档中find: https : //github.com/rackt/react-redux/blob/master/docs/api.md#examples
我能够使用“Monkeypatch”中间件工作,但是有一个更好的方法。
首先我创build了一个函数来monkeypatch子variables。 这个函数将child,dispatch和store作为参数,并返回一个更新的子variables和存储和调度的关键字:
function routeStoreMiddleware (children, dispatch, store) { return { ...children, props: { ...children.props, dispatch: dispatch, store: store } } }
然后,我简单地更新了已经可以访问调度和存储的组件来使用中间件function:
class App extends Component { render() { return ( <div> { routeStoreMiddleware(children, dispatch, store) } </div> ); } }
由于命名不当的routeStoreMiddleware函数只是返回一个更新的子对象,它仍然有效。
现在我可以派发事件并显示来自ExampleRoute组件内的数据。
从'react'导入React,{Component}; 从“../actions.js”导入{myAwesomeActionCreator}
export class Example extends Component { render () { const { dispatch, store } = this.props return ( <button onClick={ () => { dispatch(myAwesomeActionCreator()) }}>{ store.thingName }</button> ); } }
好极了!
请注意:在这里我已经阅读了很多关于如何使用redux正确创build中间件的内容,但是我还没有时间来完全理解它。 有一个比我在这里做的更好的方法。