2016-01-20 84 views
1

我想弄清楚如何從路由內部訪問REDX存儲,所以我可以從路線內調度行動。從REDX簡單路由器的兒童訪問REDX店

這裏是我的頂級組件的樣子:

class App extends Component { 
    render() { 
    return (
     <div> 
     { children } 
     </div> 
    ); 
    } 
} 

我的終極版,簡單的路由器代碼如下所示:

render(
    <Provider store={store}> 
    <Router history={history}> 
     <Route path="/" component={App}> 
     <IndexRoute component={ Home } /> 
     <Route path="/example" component={ ExampleRoute } /> 
     </Route> 
    </Router> 
    </Provider>, 
    rootElement 
) 

如果我傾倒的道具從ExampleRoute組件內,我不無法進入商店。任何幫助感謝!

回答

2

您應該使用connectreact-redux得到dispatch和當前狀態從商店。它在這裏的終極版文檔概述: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文檔中找到:https://github.com/rackt/react-redux/blob/master/docs/api.md#examples

0

我能夠得到這個與「Monkeypatch」中間件的工作,但有一個更好的方法。

首先我創建了一個函數來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組件內的數據。

import'react'中的{Component}; 進口{} myAwesomeActionCreator從」 ../actions.js'

export class Example extends Component { 
    render() { 
    const { dispatch, store } = this.props 
    return (
     <button onClick={() => { 
     dispatch(myAwesomeActionCreator()) 
     }}>{ store.thingName }</button> 
    ); 
    } 
} 

耶!

請注意: 我一直reading a lot here如何使中間件在適當的終極版,但我還沒有來得及尚未完全瞭解它。有比我在這裏做的更好的方法。