Redux 存储更新成功,但组件的 mapStateToProps 接收旧状态

IT技术 reactjs redux react-redux
2022-07-19 00:23:32

不知道是什么问题,我都试过了。这个问题最接近我的,但它没有帮助我 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]
    }
}

动作创建者

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");
            }
        );
    } }

应用程序引导

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
    );

组件连接 - 在我的props中,我收到旧数据,直到我转到下一页并返回

 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)
0个回答
没有发现任何回复~