gpt4 book ai didi

javascript - 如何在React Native应用程序中使用React hook useEffect设置每5秒渲染一次的间隔?

转载 作者:行者123 更新时间:2023-11-28 17:00:51 24 4
gpt4 key购买 nike

我有 React Native 应用程序,我通过 fetchAPI 获取数据。我创建了从 API 获取数据的自定义 Hook 。我需要每 5 秒重新渲染一次。为此,我将自定义 Hook 包装到 setInterval 中,在我的应用程序工作速度非常缓慢之后,当我导航到另一个屏幕时,我收到此错误:

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的最佳方法,因为我认为我的方法不好。

我的自定义 Hook :

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])

有关 useEffectcleanup 函数的更多信息,请参阅 this .

关于javascript - 如何在React Native应用程序中使用React hook useEffect设置每5秒渲染一次的间隔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57542264/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com