对于连接的容器,我有一个由更高级的减速器包装的减速器(如下所示)来捕获和处理错误。在componentDidMount
期间调用获取请求并且失败时,连接的容器将自行卸载componentWillUnmount
。这会导致容器中的无限循环,因为它将再次挂载,fetch将失败,容器将自行卸载。
为什么在连接组件中使用更高阶的reducer会导致这种情况?
错误处理高阶减速器:
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)));
};
答案 0 :(得分:1)
根据我们在评论中的对话:
通常,组件会卸载,因为它们的父级不再呈现它们。父母的样子是什么样的?您可能希望找到卸载组件的原因。
我不知道组件可以自行卸载(没有黑客攻击)的任何情况
答案 1 :(得分:0)
我认为您只需要捕获错误,而不是让React安装代码捕获异常。
try {
this.props.fetch(....);
}
catch (e) {
//Do whatever is appropriate to handle the fetch failure. Maybe you want...
this.setState({ error: {hasError: true, message: '' + e});
}
我认为上面的setState()调用不适合你想要的reducer实现,但这是你可以解决的一个单独问题(或者询问更多问题)。问题的主要部分似乎是停止卸载/重新安装行为。