我使用 useEffect 来触发一个名为 callCard 的函数。
这将发出 api 请求并检索数据。
我可以看到 api 请求检索数据,我什至可以看到 changeCards 更改了 fetchedCard 的数据,但是,返回的数据不会与新数据重新映射。
我知道新数据在这一点上存在,因为我可以在地图上方控制台日志并查看它在那里。
无论出于何种原因,一旦 fetchedCard 的状态被更改,数据似乎就不想重新映射。
但是,当用户滚动到页面底部时,我也会在滚动上使用此功能。
发生这种情况时,将调用该函数,正确呈现、映射和显示数据。
PlayerPage = (props) => {
const [fetchedCards, changeCards] = useState([])
const [currentUser, updateUser] = useState('')
const [skip, setSkip] = useState(0)
const [load, setLoad] = useState(false)
callCards = (passedSkip) => {
let requestParams =
props.player ?
`players=${props.player}&startDate=2019-03-20T03:10:43.990Z&sort=createdAt`:
props.team ?
`team=${props.team}&startDate=2019-03-20T03:10:43.990Z&sort=createdAt` :
props.league ?
`league=${props.league}&startDate=2019-03-20T03:10:43.990Z&sort=createdAt`:
null
let finalSkip = skip === 0 ? skip : passedSkip
console.log(`http://${BASE}:4000/reports?${requestParams}&skip=${finalSkip}`)
axios.get(`http://${BASE}:4000/reports?${requestParams}&skip=${finalSkip}`)
.then(response => {
let combinedCards = fetchedCards
combinedCards.push(...response.data)
console.log(combinedCards)
changeCards(combinedCards)
setLoad(false)
})
}
getMoreCards = (e) => {
var windowHeight = Dimensions.get('window').height,
height = e.nativeEvent.contentSize.height,
offset = e.nativeEvent.contentOffset.y;
if( windowHeight + offset >= height && load !== true ){
setLoad(true)
setSkip(skip + 2)
callCards(skip + 2)
}
}
useEffect(() =>{
callCards(0)
}, [])
return(
<View>
{console.log(fetchedCards)}
<View>
<Header
rounded
>
<View>
<NativeText
onPress={() => {
Actions.pop()
}}
style ={{color: '#006FFF', fontSize: 12, fontFamily: 'Montserrat-Regular'}}
>
Back
</NativeText>
</View>
</Header>
</View>
<ScrollView
style={{backgroundColor: 'white', height: '100%'}}
onScroll={e=> getMoreCards(e)}
scrollEventThrottle={16}
>
<View style={{position: 'relative', paddingTop: '3%', paddingBottom: '35%'}} >
{
fetchedCards !== '' ?
fetchedCards.map((v,i) => {
return(
<View key={i}>
<Text
style={{color: '#58395C'}}>{v.player.player_name} - </Text>
</View>
)
})
: null
}
</View>
</ScrollView>
</View>
)
}
export default PlayerPage
这是因为您正在改变数组。
您需要改为执行以下操作:
let combinedCards = [...fetchedCards]
combinedCards.push(response.data)
console.log(combinedCards)
changeCards(combinedCards)
(或只是做(
let combinedCards = [...fetchedCards, response.data]