2016-12-24 37 views
1

我在React + Redux + redux-thunk代码库中工作,我看到一些奇怪的行为。如果我尝试在componentWillMount中执行TWO操作,则第二个操作将无限循环。在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()是一个简单的状态更新。第二个操作是对服务器进行提取。此操作文件:

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电话会不断重复。

任何帮助将不胜感激,我似乎已经打了一堵墙。

回答

4

我相信破坏无限循环的最佳场所是在Redux reducer中。 Reducer是您必须决定是否要更新应用程序状态的地方 - >会触发组件的重新渲染 - >会触发获取操作。

因此,尽量设置一些reducer条件,您可以在其中识别出之前已经获取的状态,并且不打算更新状态。