Mark Qian
Mark Qian

Reputation: 773

React View is not updated with redux

The react view is not updated (the render is never called) but the reducer was invoked.

I have the following:

1). the react view: I a field in the root state to determent if I need to show "TodoList" or "HousingInfo"

export default class RightPane extends React.Component{
static contextTypes = {
    store: React.PropTypes.object
  }

render(){
    let store = this.context.store;
    let curPage = store.getState()["mainRightPanePage"].currentPage;
    return (
         <div>
             {(store.getState()["mainRightPanePage"].currentPage==="TodoList") && <TodoList/>}
             {(store.getState()["mainRightPanePage"].currentPage==="HousingInfo") && <HousingInfo/>}
         </div>
    )
}

}

2). the action dispatching in another component

 export default class LeftPane extends React.Component{
    static contextTypes = {
         store: React.PropTypes.object
      }
    handleink(pageId, e) {
        e.preventDefault();
        let store = this.context.store;
        store.dispatch({'type':'switchPage', 'pageId':pageId});
    ...
}

3). the reducer: the following reducer was invoked

 const mainRightPanePage = (state = {'currentPage':'TodoList'}, action) => {
   switch (action.type) {
     case 'switchPage':
       return Object.assign({}, state, {
          currentPage: action.pageId
      })
  default:
    return state
  }
}

 export default mainRightPanePage

What did I miss?

thanks

Upvotes: 0

Views: 70

Answers (1)

Bartek Fryzowicz
Bartek Fryzowicz

Reputation: 6674

In your example the RightPane component is not aware that Redux state was updated because you haven't subscribed to Redux state changes. You can subscribe to Redux store directly using subscribe method or you can connect your components to Redux store using connect method from React-Redux (recommended):

import {connect} from 'react-redux';
...

class RightPane extends React.Component{
    ...
    render(){
        let currentPage = this.props.currentPage;
        return (
             <div>
                 {(currentPage === "TodoList") && <TodoList/>}
                 {(currentPage === "HousingInfo") && <HousingInfo/>}
             </div>
        )
    }
}


const mapStateToProps = (state) => {
    return {
        currentPage: state.mainRightPanePage.currentPage
    }
};

export default connect(
    mapStateToProps
)(RightPane);

Upvotes: 4

Related Questions