我在 React + Redux + redux-thunk 代码库中工作,我看到了一些奇怪的行为。如果我尝试在 componentWillMount 中执行两个 操作,第二个操作将无限循环。
这是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()
是一个简单的状态更新。第二个操作对服务器进行提取。 Action 文件在这里:
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 });
});
};
}
如果我要从 componentWillMount
中删除第一个操作 openLoader()
,则不会发生无限循环。否则 fetch
调用将不断重复。
任何帮助将不胜感激,我似乎碰壁了。
最佳答案
我认为打破无限循环的最佳位置是在 Redux reducer 中。 Reducer 是您必须决定是否要更新应用程序状态的地方 -> 将触发组件的重新渲染 -> 将触发获取操作。
因此,请尝试设置一些 reducer 条件,让您可以识别之前已经获取的状态,并且您不会更新状态。
关于javascript - 在 componentWillMount 中调度时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41310039/