Reactjs Redux商店更新成功,但组件';s MapStateTrops接收旧状态
不知道是什么问题,我什么都试过了。 这个问题与我的最为接近,但对我没有帮助 减速器 动作创造者Reactjs Redux商店更新成功,但组件';s MapStateTrops接收旧状态,reactjs,redux,react-redux,Reactjs,Redux,React Redux,不知道是什么问题,我什么都试过了。 这个问题与我的最为接近,但对我没有帮助 减速器 动作创造者 export function loadAll(id: number) { return function(dispatch: Dispatch) { return fetch(`http://localhost:4000/test`, { method: 'GET', }) .then((re
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
);
您似乎在MapStateTops中返回回调函数?尝试将其更改为:const-mapStateToProps=(state:any,ownProps:any)=>{return{sections:state.sections | | |[],}}@StephanOlsen OMG,谢谢你兄弟)另外,请注意,你可以使用一种更简单的
mapspatch
。只需将所有动作创建者放在一个对象中,并将其传递给connect
,例如:const-mapspatch={saveSection,loadAll,removeSection}
。当我们进行此操作时,reducer中switch语句的默认大小写应该只返回state。通过返回[…状态],您将导致不必要的应用程序重新加载,因为没有任何道具被更改。感谢@markerikson的响应,是的,我需要一些重构)
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
);
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)