使用连接的容器,我有一个由更高阶的减速器(如下所示)包裹的减速器,以捕获和处理错误。在调用 fetch 请求componentDidMount
失败时,连接的容器将自行卸载componentWillUnmount
。这会导致容器中的无限循环,因为它将再次挂载,获取将失败,并且容器将自行卸载。
任何想法为什么在连接组件中有更高阶的减速器会导致这种情况?
错误处理高阶减速器:
export const errorHandler = (reducer: (state: any, action: { type: string }, initialState: any) => {}) => {
const errorState = fromJS({
error: {
hasError: false,
message: "",
},
});
const initialState = errorState.merge(reducer(undefined, { type: undefined }, undefined));
return (state = initialState, action) => {
switch (action.type) {
case ACTIONS.SET_ERROR:
return state.setIn(["error", "hasError"], true)
.setIn(["error", "message"], action.message);
case ACTIONS.CLEAR_ERROR:
return state.set("error", errorState.get("error"));
default:
return reducer(state, action, initialState);
}
};
};
示例容器:
class Page extends Component {
componentDidMount() {
this.props.fetch(....);
}
componentWillUnmount() {
this.props.clearData();
this.props.cancelRequests();
}
}
export default connect(
(state) => ({
error: state.data.get("error", ""),
}),
{
clearError,
clearData,
cancelRequests,
},
)(Page);
减速器示例:
export fetch = () => ({
type: ACTIONS.FETCH
});
export default errorHandler((state, action) => {
switch(action.type) {
default:
return state;
}
}));
史诗:
export const fetch = (action$: any, store: any, api: API) => {
return action$.ofType(ACTIONS.FETCH)
.mergeMap((action: any) =>
fromPromise(api.fetch(action.data))
.pluck("Data")
.map(data) =>
fetchFulfilled(data),
)
.catch((response) => {
const toPromise = typeof response.json === "function" ? response.json() : new Promise((resolve) => resolve(response));
return fromPromise(toPromise)
.pluck("Message")
.map((Message: string) =>
setError(Message));
})
.takeUntil(action$.ofType(ACTIONS.CANCEL_REQUESTS)));
};