JavaScript
x
31
31
1
export default function CreatePage() {
2
let [state,setState]=useState({})
3
let flag=true
4
useEffect(()=>{
5
if(flag){
6
axios.get('http://192.168.43.151:3001/data').then((res)=>
7
{
8
console.log(res.data)
9
setState({res.data})
10
flag=false
11
console.log(false)
12
13
}
14
).catch((err)=>{console.log(err)}).finally(()=>{flag=false})
15
16
}
17
18
19
})
20
21
22
return (
23
<View >
24
<Text>hh</Text>
25
<Icon name="heart" size={24} color="#4F8EF7" />
26
<Text>first page</Text>
27
<Text>{state.name}</Text>
28
29
</View>
30
)
31
}
after the code is executed ,the terminal continues showing :
JavaScript
1
7
1
{"age": 25, "name": "connor", "password": "123456"}
2
LOG false
3
LOG {"age": 25, "name": "connor", "password": "123456"}
4
LOG false
5
LOG {"age": 25, "name": "connor", "password": "123456"}
6
LOG false
7
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
JavaScript
1
26
26
1
const [state,setState] = useState({});
2
const [flag,setFlag] = useState(true);
3
useEffect(()=>{
4
if(flag){
5
axios.get('http://192.168.43.151:3001/data').then((res)=>
6
{
7
console.log(res.data)
8
setState({res.data})
9
setFlag(false)
10
console.log(false)
11
12
}
13
).catch((err)=>{console.log(err)}).finally(()=>{flag=false})
14
15
}
16
17
18
},[])
19
20
21
if(flag) {
22
return <LoadingElem />
23
}
24
25
26