gpt4 book ai didi

javascript - React/Redux - 为什么这个 Promise.all 在调度后继续执行?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:40:58 26 4
gpt4 key购买 nike

我有一个使用 redux 的 React-Native 项目。我执行了一些 axios 调用,基本上,该应用程序运行良好。但是,有一件事是不对的。我在调度之前放置了一个 console.log,甚至应用程序加载和呈现一切都很好,我看到 console.log 在控制台中不断循环。我不确定为什么会这样,但我在 Javascript 中阅读了“run to completion”概念,这可能就是原因。尽管如此,我还是想不通。

有什么办法可以解决这个问题吗?非常感谢。

更新:这里是在 renderEtiquetas() 函数中调用操作的组件。这可能是导致此循环的原因,因为它在每个重新渲染周期上运行(对此不确定)。我尝试将调用移动到 componentDidMount() 但它似乎没有运行。

我是 React 的新手,所以我可能在做一些愚蠢的事情。

组件.js

class EtiquetasList extends Component {

componentDidMount() {
this.props.FetchEtiquetas();
}


renderEtiquetas() {
if ( this.props.etiquetas.length == 0 ) {
return <ActivityIndicator size="large" color="#00ff00" />
} else {
this.props.FetchGalleries( this.props.etiquetas );
if ( this.props.galleries.length > 0 ) {
return this.props.etiquetas.map(etiqueta =>
<EtiquetaDetail key={etiqueta.id} etiqueta={etiqueta} galleries={ this.props.galleries } />
);
}
}
}

render() {
return (
<ScrollView>
{ this.renderEtiquetas() }
</ScrollView>
);

}

}

const mapStateToProps = (state) => {

return {
etiquetas: state.data.etiquetas,
isMounted: state.data.isMounted,
galleries: state.slides.entries
};
};

export default connect(mapStateToProps, { FetchEtiquetas, FetchGalleries })(EtiquetasList);

Action .js

export function FetchGalleries( etiquetas ) {

return function (dispatch) {
return Promise.all(
etiquetas.map( record =>
axios.get('mydomain.com/?id='+record.id)
)).then(galleries => {

let my_data = [];
let data_json = '';

galleries.map( record => {
record.data.map( subrecord => {
// this is simplified for this example, it works as intended
data_json = data_json + '{ title: "' + subrecord.title+'"}';
});

my_data.push( data_json );

});

console.log( my_data ); // this keeps printing in the console
return dispatch({ type: FETCH_GALLERIES_SUCCESS, payload: my_data });

});
}
}

最佳答案

啊哈,FetchGalleries 运行在 render 函数内部,它会导致 action->render->action->render 死循环。

编辑:尝试将您的 FetchGalleriesFetchEtiquetas 合并到一个操作中如何:

export const fetchGalleries = () => {
return function (dispatch) {
return axios.get('/path/to/etiquetas').then(etiquetas => {
dispatch({ type: FETCH_ETIQUETAS_SUCCESS, payload: etiquetas });
// ... your previous promise all code
});
}
}

并且只需要在 componentDidMount 调用这个新的 fetchGalleries

关于javascript - React/Redux - 为什么这个 Promise.all 在调度后继续执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49000747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com