React Native Post请求在显示数组时会导致无限循环



我正在从React Native Navigation中的侧菜单中导航到此'历史标签。有一个用户名,我可以为此获得所有"预订",但是我可以在警告标签中看到,即使在安装了组件之后,也有无数的请求,因此可能是由SetState引起的无限环路。我应该在哪里称呼Gethistory((,例如仅提出一个请求,除非当然要重新加载组件。谢谢!

constructor(props){
        super(props);
        this.state = {
            loggedUser: 'none',
            bookingsInfo: []
        }
    }
    getData = async () => {
        try {
          const value = await AsyncStorage.getItem('loggedUser')
          if(value !== null) {
            this.setState({
                loggedUser: value
            })
          }
        } catch(e) {
            console.error(e);
        }
    }
    getHistory() {
            fetch('https://porsche.e-twow.uk/reactnative/istoric.php', {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'Cache-Control': 'no-cache, no-store'
                },
                body: JSON.stringify({
                    username: this.state.loggedUser
                })
            })
            .then((response) => response.json())
            .then((data) => {
                this.setState({
                    bookingsInfo: data
                });
            })
            .catch((error) => {
                console.error(error);
            });
    }
    componentDidMount() {
        this.getData();
    }
    render() {
        this.getHistory();
        return (
            <View style={styles.view}>
                <ScrollView style={styles.scrollView}>
                    {
                        this.getHistory()
                    }
                    {
                        this.state.bookingsInfo ? this.state.bookingsInfo.map((item, index) => {
                            return (
                                <View style={styles.mainButton} key={item.id_scooter}>
                                    <Text style={styles.mainButtonText}>Scooter-ul {item.id_scooter}</Text>
                                    <Text style={styles.mainButtonText}>Data start: {item.start}</Text>
                                    <Text style={styles.mainButtonText}>Data final: {item.end}</Text>
                                </View>
                            )
                        }) : null
                    }
                </ScrollView>
                <Footer/>
            </View>
        );
    }
}

您在渲染中设置状态。在这里添加setState使您的组件成为生产无限循环的竞争者。 将Gethistory放在componentDidmount中。

  componentDidMount() {
   this.getHistory();
 }

最新更新