在 componentWillMount 中调度时无限循环
Infinite loop when dispatching in componentWillMount
我在 React + Redux + redux-thunk 代码库中工作,我看到了一些奇怪的行为。如果我尝试在 componentWillMount 中执行 TWO 个动作,第二个动作将无限循环。
这是 componentWillMount
:
componentWillMount() {
const { actions } = this.props;
// Action #1 (synchronous)
actions.openLoader();
// Action #2 (promise-based fetch)
actions.getListingsPurchased().then(() => {
actions.closeLoader();
})
.catch(error => {
console.error(error);
});
}
第一个动作,openLoader()
是一个简单的状态更新。第二个操作对服务器进行提取。此处的操作文件:
export function openLoader() {
return {
type: TYPES.SET_LOADER_OPEN
};
}
export function getListingsPurchased() {
return dispatch => {
return fetch'URL GOES HERE', { 'credentials': 'include' })
.then(response => {
return response.json();
})
.then(response => {
return dispatch({ type: TYPES.SET_LISTINGS, data: response.data });
});
};
}
如果我要 删除 第一个操作 openLoader()
从 componentWillMount
无限循环不会发生。否则 fetch
调用将不断重复。
任何帮助将不胜感激,我好像碰壁了。
我认为打破无限循环的最佳位置是在 Redux reducer 中。 Reducer 是您必须决定是否要更新应用程序状态的地方 -> 将触发组件的重新渲染 -> 将触发获取操作。
因此,请尝试设置一些 reducer 条件,让您可以识别出之前已获取状态并且您不会更新状态。
我在 React + Redux + redux-thunk 代码库中工作,我看到了一些奇怪的行为。如果我尝试在 componentWillMount 中执行 TWO 个动作,第二个动作将无限循环。
这是 componentWillMount
:
componentWillMount() {
const { actions } = this.props;
// Action #1 (synchronous)
actions.openLoader();
// Action #2 (promise-based fetch)
actions.getListingsPurchased().then(() => {
actions.closeLoader();
})
.catch(error => {
console.error(error);
});
}
第一个动作,openLoader()
是一个简单的状态更新。第二个操作对服务器进行提取。此处的操作文件:
export function openLoader() {
return {
type: TYPES.SET_LOADER_OPEN
};
}
export function getListingsPurchased() {
return dispatch => {
return fetch'URL GOES HERE', { 'credentials': 'include' })
.then(response => {
return response.json();
})
.then(response => {
return dispatch({ type: TYPES.SET_LISTINGS, data: response.data });
});
};
}
如果我要 删除 第一个操作 openLoader()
从 componentWillMount
无限循环不会发生。否则 fetch
调用将不断重复。
任何帮助将不胜感激,我好像碰壁了。
我认为打破无限循环的最佳位置是在 Redux reducer 中。 Reducer 是您必须决定是否要更新应用程序状态的地方 -> 将触发组件的重新渲染 -> 将触发获取操作。
因此,请尝试设置一些 reducer 条件,让您可以识别出之前已获取状态并且您不会更新状态。