2016-11-08 75 views
1

我被困在一個似乎很明顯的問題上:路由器的根組件並未被訂閱存儲更改,即使調用了mapStateToProps也沒有收到道具。根路由組件沒有連接到redux

我的路線定義爲普通的對象:

const createRoutes = (store) => { 
    path: '/', 
    component: RootComponent, 
    indexRoute: Home, 
    childRoutes: [ 
     SubRoute 
    ] 
} 
export default createRoutes 

於是我進口創造應用程序時,這個對象:

let render =() => { 
    const routes = require('./routes').default(store); 
    ReactDOM.render(
     <AppContainer store={store} routes={routes} />, 
     MOUNT_NODE                  
    ) 
} 

我RootComponent看起來是這樣的:

const RootComponent = ({address, action}) => { 
    <div> 
     {console.log('addr: ' + address)} 
     <button onClick={action}>test</button> 
    </div> 
} 
const mapStateToProps = (state) => { 
    console.log('mapStateToProps'); 
    return {address: state.address}; 
} 
const mapDispatchToProps = (dispatch) => { 
    action = (evt) => { 
     console.log('mapDispatchToProps'); 
     dispatch({type: 'TEST', payload: {address: 'xxx'}}); 
    } 
} 
export default connect(mapStateToProps, mapDispatchToProps)(RootComponent) 

當我點擊按鈕,調度工作,因爲我可以在DevTools中看到狀態已更改。 mapStateToProps和mapDispatchToProps也被調用,但我的RootComponent永遠不會更新。

如果我爲子路由做同樣的代碼,一切正常!關於爲什麼RootComponent沒有訂閱商店的任何想法?

編輯:順便說一句,<AppContainer />使用<Provider />react-redux。該代碼是這樣的:

class AppContainer extends Component { 
    render() { 
     const { routes, store } = this.props 

     return (
      <Provider store={store}> 
       <Router history={browserHistory} routes={routes} /> 
      </Provider> 
     ) 
    } 
} 

回答

-2

好了,發現了問題:原來的代碼mapStateToProps沒有從國家得到正確的價值觀(儘管我已打印狀態的百萬倍,並沒有意識到)。所以,狀態沒有變化,組件顯然沒有被更新。

+0

我有同樣的問題。你是如何使'mapStateToProps'接收狀態的? – ilyo

+0

'mapStatetoProps'實際上正確地接收了狀態。但是我錯誤地設置了組件的狀態。並且由於組件的狀態沒有改變(因爲它被設置不正確),組件沒有被更新。 – danielnovy

+1

回答你自己的問題沒有意義,只能說「我發現了一個正確的方法來使它工作!」請提供使其工作的實際代碼,這樣其他人也可以從中受益。 – ilyo

1

您沒有提及利用反應 - 終極版的<Provider />成分的,我猜你一定在某處定義,但如果你不是:

它是<Provider />,使商店可用於您在容器組件中進行的連接調用。

Check out the docs for more info

+0

感謝您的回覆。是的,我添加了'',將用該信息更新代碼。 – danielnovy

相關問題