简体   繁体   中英

React Native structure causes Axios to loop HTTP requests

I'm developing an iOS application through Expo and React Native. I have started up the project as a blank project through:

> expo init
> tabs

and have thus started a basic project with react-navigation. Below is a picture of my file structure. The only things I've added are the three screens HomeScreen, FunctionsScreen and ServantsScreen. (Each named after a resource that will be fetched from a REST API).

Screenshot of file structure

Following code is from one of my screens, ServantsScreen, which is imported into the BottomTabNavigator.js, as listed further down below. (The flatlist contains dummy data for now, will populate with api call once it works.)

export default function ServantsScreen() {
    const [servants, setServants] = useState({})
    axios.get('http://18.197.158.213/servants').then(({data}) => {
        setServants(data.servants);
    });
    console.log(servants)
    return (

      <SafeAreaView
          style={{
          flex: 1,
          alignItems: 'center',
          justifyContent: 'center',
        }}>

        <FlatList 
          data={
            [{name: 'a'}, {name: 'b'}, {name: 'c'}, {name: 'd'}]
          } 
          renderItem={
            ({ item }) => <Text>{item.name}</Text>
          } 
          keyExtractor={(item, index) => index.toString()}
        />

      </SafeAreaView>
    );
}

Import into BottomTabNavigator

      import ServantsScreen from '../screens/ServantsScreen'
      <BottomTab.Screen
        name="Tjänare"
        component={ServantsScreen}
        options={{
          title: 'Tjänare',
          tabBarIcon: ({ focused }) => <TabBarIcon focused={focused} name="md-book" />,
        }}
      />

Navigation works perfectly, as expected. But when debugging, I see that the following code is being called over and over again in a never-ending loop. Ie the console.log(servants) keeps spamming the console, which I presume is cause the whole function is being called over and over again. I am wondering how I can fix this, so each Screen makes it's own (or a master page that distributes the data to the different pages?) REST API call through axios, and then displays the data.

const [servants, setServants] = useState({})
    axios.get('http://18.197.158.213/servants').then(({data}) => {
        setServants(data.servants);
    });
    console.log(servants)

How should I handle this problem?

You should wrap the axios request into a useEffect hook like so:

This way it will trigger only once when the component is mounted.

React.useEffect(() => {
    axios.get('http://18.197.158.213/servants').then(({data}) => {
        setServants(data.servants);
    });
},[]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM