Redux store updates successfully, but component's mapStateToProps receiving old state

白昼怎懂夜的黑 提交于 2020-04-30 05:12:16

问题


Don't know what the problem, i have tried everything. this issue is closest to mine, but it not helped me https://github.com/reduxjs/redux/issues/585 Reducer

export default (state = [], action: any) => {
    switch (action.type) {
        case "GET_ALL":
            return [...action.sections];
        case "ADD_ONE":
            return [...state, action.section];
        case "REMOVE":
            return state.filter((section: Section) => section.id !== action.id);
        default:
            return [...state]
    }
}

Action Creator

export function loadAll(id: number) {
    return function(dispatch: Dispatch) {
        return fetch(`http://localhost:4000/test`, {  
                method: 'GET',
            })
            .then((response: any) => response.json())
            .then((sections: Section[]) => {
                dispatch({
                    type: "GET_ALL",
                    sections
                });
            },
            err => {
                 throw new Error("Network error");
            }
        );
    } }

Application Bootstrap

const composedEnhancers = compose(
    applyMiddleware(thunk, routerMiddleware(history)),
);

const store = createStore(
    connectRouter(history)(combineReducers({
            sections: sectionReducer, 
        })),
    initialState, //is equal to {}
    composedEnhancers
);

    const target = document.querySelector('#root');

    render(
        <Provider store={store}>
            <ConnectedRouter history={history}>
          <div>
            <main className="appContent">
                <Route exact={true} path="/" component={TestPage} />  
            </main>
          </div>
            </ConnectedRouter>
        </Provider>,
        target
    );

Component connection - here in my props i receive old data, until i go to next page and return back

 const mapDispatchToProps = (dispatch: Dispatch, props: any) => {
    return {
        saveSection: (section: Section) => dispatch(saveSection(section) as any),
        loadAll: (id: number) => dispatch(loadAll(id) as any),
        removeSection: (sectionId: number) => dispatch(removeSection(sectionId) as any),
    }
}
const mapStateToProps = ((state: any, ownProps: any) => (() => {
return {
    sections: state.sections || [],
}
}));

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(TestPage)

来源:https://stackoverflow.com/questions/51754014/redux-store-updates-successfully-but-components-mapstatetoprops-receiving-old

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!