简体   繁体   中英

What are the reasons to have React-redux store state and mapStateToProps state be different?

I'm getting in a situation that when I'm dispatching an action, store state is changing as it should but my connected components mapStateToProps callback state is not reflecting the new changes in the store.

What can be the reasons for this?

configureStore.js

export default () => {
    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

    const store = createStore(
        combineReducers({
            concepts: conceptReducer,
            conceptModal: conceptModalReducer,
            cards: cardReducer,
            cardModal: cardModalReducer,
        }),
        composeEnhancers(applyMiddleware(queryApi))
    );

    store.subscribe(() => {
        console.log('store notification:', store.getState());
    })

    return store;
};

Reducer.js

case "UPDATE_CONCEPT_SUCCESS": {
    let concepts = [...state.data].map((concept) => {
        if (concept.id === action.id) {
            return { ...concept, ...action.concept };
        }
        return concept;
    });

    /* Even with return below, mapStateToProps state parameter still returns the old state */
    // return {'data': [{id:1},{id:2}]}
    return { ...state, pending: false, lastErrorCode: null, lastErrorMessage: null, data: concepts };
    break;
}

CardModal.js

export default connect((state, p) => (() => {
    // the console.log below returns the old state
    console.log('connect called', state);

    return ({
        isThemeDark: state.common.isThemeDark,

        allConceptsData: allConcepts(state.concepts.data),
        conceptsData: allConceptsForTopicId(state.concepts.data, state.cardModal.topicId),
    })
}))(CardModal);

Your mapStateToProps is returning a function, not the new state.

Try this instead:

export default connect((state, p) => {

  // the console.log below returns the old state
  console.log('connect called', state);

  return {
    isThemeDark: state.common.isThemeDark,

    allConceptsData: allConcepts(state.concepts.data),
    conceptsData: allConceptsForTopicId(state.concepts.data, state.cardModal.topicId),
  };
}))(CardModal);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM