Skip to content
Advertisement

react native useEffect run into dead loop:

export default function CreatePage() {
let [state,setState]=useState({})
let flag=true
useEffect(()=>{
    if(flag){
        axios.get('http://192.168.43.151:3001/data').then((res)=>
    {
        console.log(res.data)
        setState({...res.data})
        flag=false
        console.log(false)
      
    }
    ).catch((err)=>{console.log(err)}).finally(()=>{flag=false})

    }

    
})


return (
    <View >
        <Text>hh</Text>
        <Icon name="heart" size={24} color="#4F8EF7" />
        <Text>first page</Text>
        <Text>{state.name}</Text>
        
    </View>
)

}

after the code is executed ,the terminal continues showing :

    {"age": 25, "name": "connor", "password": "123456"}
 LOG  false
 LOG  {"age": 25, "name": "connor", "password": "123456"}
 LOG  false
 LOG  {"age": 25, "name": "connor", "password": "123456"}
 LOG  false

i have confusion about this ,useEffect function should be rendered once .However ,it seems continuing to be redered .

Advertisement

Answer

You did not add a dependency array to the useEffect function. Therefore, it is bound to be an infinite reRendering.

And react does not recommend let. Use the status value.

You can add a dependency array

const [state,setState] = useState({});
const [flag,setFlag] = useState(true);
useEffect(()=>{
    if(flag){
        axios.get('http://192.168.43.151:3001/data').then((res)=>
    {
        console.log(res.data)
        setState({...res.data})
        setFlag(false)
        console.log(false)
      
    }
    ).catch((err)=>{console.log(err)}).finally(()=>{flag=false})

    }

    
},[])


if(flag) {
   return <LoadingElem />
}

...
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement