学习Context
,Provider
我试图弄清楚如何在检测是否处于焦点时在屏幕组件中实现我state
的 from 。Context
import { useIsFocused } from '@react-navigation/native'
const isFocused = useIsFocused()
根据研究,我正确地引入Context
了:
import React, { useContext, useEffect, useState } from 'react'
import { Context as TrackContext } from '../context/TrackContext'
const {
state: { data },
fetchTracks,
} = useContext(TrackContext)
在我的上下文文件(精简)中,我Reducer
正在工作,我能够得到我的payload
:
// Context
import createContext from './createContext'
// Mock Data
import locations from '../data/locations'
const trackReducer = (state, action) => {
switch (action.type) {
case 'fetch_tracks':
console.log('payload:', action.payload.length)
return action.payload
default:
return state
}
}
const fetchTracks = dispatch => async () => {
console.log('fetching tracks')
dispatch({ type: 'fetch_tracks', payload: locations })
}
export const { Provider, Context } = createContext(
trackReducer,
{
fetchTracks,
},
[],
)
但是当我尝试检索state
焦点时true
它不起作用时:
useEffect(() => {
isFocused ? fetchTracks() : null
}, [isFocused])
return (
<FlatList
data={data}
keyExtractor={item => item._id}
renderItem={({ item }) => {
console.log('item detected')
return (
<TouchableOpacity
onPress={() => navigation.navigate('TrackDetailScreen', { _id: item._id })}
>
<Component />
</TouchableOpacity>
)
}}
/>
)
我尝试了一种替代方法useState
并写道:
const [trackData, setTrackData] = useState([])
useEffect(() => {
isFocused ? setTrackData(fetchTracks()) : null
}, [isFocused])
return (
<FlatList
data={trackData}
keyExtractor={item => item._id}
renderItem={({ item }) => {
console.log('item detected')
return (
<TouchableOpacity
onPress={() => navigation.navigate('TrackDetailScreen', { _id: item._id })}
>
<Component />
</TouchableOpacity>
)
}}
/>
)
这两种方法都不起作用或将带有数据的屏幕组件重新渲染到FlatList
. 在我的屏幕组件中,我应该如何Context
仅在屏幕为时检索inFocus
状态数据true
?