我正在使用两个
useFocusEffect()
钩子(来自react-navigation-v6)。
当下面代码中显示的屏幕处于焦点时,它会渲染两次,而不是像我预期的那样渲染一次(console.log() 运行两次)。为什么会出现这种情况?
import { useFocusEffect } from '@react-navigation/native';
import axios from 'axios';
import React, { useState } from 'react'
import { View } from 'react-native'
let renderCount = 0;
function TestScreen() {
const [myState1, setMyState1] = useState<any>();
const [myState2, setMyState2] = useState<any>();
renderCount++;
console.log("component render number: ", renderCount);
// First useFocusEffect
useFocusEffect(
React.useCallback(() => {
fetchAPIData1()
}, [])
);
// Second useFocusEffect
useFocusEffect(
React.useCallback(() => {
fetchAPIData2()
}, [])
);
const fetchAPIData1 = async () => {
const { data } = await axios.get<any>(
'https://dummyjson.com/quotes?limit=30')
setMyState2(data)
}
const fetchAPIData2 = async () => {
const { data } = await axios.get<any>(
'https://dummyjson.com/quotes?limit=30')
setMyState2(data)
}
return (
<View></View>
)
}
export default TestScreen
useFocusEffect(
React.useCallback(() => {
fetchAPIData1()
fetchAPIData2()
}, [])
);
如果您只想进行一次渲染,您可以 Promise.all 两个 API 调用并设置一次状态,或者您可以利用 React.memo HOC 在子组件重新渲染期间禁用任何不需要的视觉变化。