如何在 React Native 应用程序中使用 React hook useEffect 每 5 秒渲染一次 setInterval? [英] How to setInterval for every 5 second render with React hook useEffect in React Native app?
问题描述
我有 React Native
应用程序,我通过 fetch
从 API
获取数据.我创建了从 API
获取数据的自定义钩子.我需要每 5 秒重新渲染一次.为此,我将我的自定义钩子包装到 setInterval 并且在我的应用程序变得非常缓慢并且当我导航到另一个屏幕时出现此错误后:
I have React Native
app and I get data from API
by fetch
. I created custom hook that get data from API
. And i need to re-render it every 5 seconds. For it I wrapped my custom hook to setInterval and after my app become work very slowly and when I navigate to another screen I get this error:
无法对卸载的组件执行 React 状态更新.这是无操作,但它表示您的应用程序中存在内存泄漏.修理,在 useEffect 清理中取消所有订阅和异步任务功能.
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
你能告诉我如何解决这个错误吗,哪种方法是 setInterval
的最佳方法,因为我觉得我的方法不好.
Can you tell me please how can I solve this bug and which will be the best way to setInterval
, because I think my way is not good.
我的自定义钩子:
export const useFetch = url => {
const [state, setState] = useState({ data: null, error: false, loading: true })
useEffect(() => {
setInterval(() => {
setState(state => ({ data: state.data, error: false, loading: true }))
fetch(url)
.then(data => data.json())
.then(obj =>
Object.keys(obj).map(key => {
let newData = obj[key]
newData.key = key
return newData
})
)
.then(newData => setState({ data: newData, error: false, loading: false }))
.catch(function(error) {
console.log(error)
setState({ data: null, error: true, loading: false })
})
}, 5000)
}, [url, useState])
useEffect(() => () => console.log('unmount'), [])
return state
}
我的组件:
const ChartsScreen = ({ navigation }) => {
const { container } = styles
const url = 'https://poloniex.com/public?command=returnTicker'
const { data, error, loading } = useFetch(url)
const percentColorHandler = number => {
return number >= 0 ? true : false
}
return (
<View style={container}>
<ProjectStatusBar />
<IconsHeader
dataError={false}
header="Charts"
leftIconName="ios-arrow-back"
leftIconPress={() => navigation.navigate('Welcome')}
/>
<ChartsHeader />
<ActivityIndicator animating={loading} color="#068485" style={{ top: HP('30%') }} size="small" />
<FlatList
data={data}
keyExtractor={item => item.key}
renderItem={({ item }) => (
<CryptoItem
name={item.key}
highBid={item.highestBid}
lastBid={item.last}
percent={item.percentChange}
percentColor={percentColorHandler(item.percentChange)}
/>
)}
/>
</View>
)
}
推荐答案
你需要清除你的间隔
,
useEffect(() => {
const intervalId = setInterval(() => { //assign interval to a variable to clear it.
setState(state => ({ data: state.data, error: false, loading: true }))
fetch(url)
.then(data => data.json())
.then(obj =>
Object.keys(obj).map(key => {
let newData = obj[key]
newData.key = key
return newData
})
)
.then(newData => setState({ data: newData, error: false, loading: false }))
.catch(function(error) {
console.log(error)
setState({ data: null, error: true, loading: false })
})
}, 5000)
return () => clearInterval(intervalId); //This is important
}, [url, useState])
有关 useEffect
中 cleanup
函数的更多信息,请参阅 这个.
For more about cleanup
functions in useEffect
refer to this.
这篇关于如何在 React Native 应用程序中使用 React hook useEffect 每 5 秒渲染一次 setInterval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!