我试图在其他帖子和论坛中搜索该错误的解决方案。但是,要么没有人解决了这些问题,要么这些问题实际上并没有像我正在做的一样。我收到一条错误消息:“不变违例,试图获取超出范围索引的帧”。当我尝试将数据从戳API输入到Flatlist时,会发生这种情况。请参见下面的代码。
import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator } from "react-native";
import { GlobalStyles } from "../styles/GlobalStyles";
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: []
}
}
componentDidMount() {
fetch("https://pokeapi.co/api/v2/pokemon/")
.then((res)=> res.json())
.then((response)=> {
this.setState({
isLoading: false,
dataSource: response
})
console.log(response)
})
}
render() {
const showIndicator = this.state.isLoading == true ? <ActivityIndicator size="large" color="#0000ff" /> : null;
return(
<View style={GlobalStyles.container}>
<View style={GlobalStyles.activityIndicator}>{showIndicator}</View>
<FlatList data={this.state.dataSource} renderItem={({item})=> {
return(
<View>
<Text>{item.name}</Text>
</View>
)
}}/>
<Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
</View>
)
}
}
export default Home;
最佳答案
您做错了的是发送this.state.datasource
是您的数据属性,您需要发送this.state.dataSource.results
import React, { useState } from "react";
import { View, Text , Button, FlatList, ActivityIndicator } from "react-native";
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
dataSource: []
}
}
componentDidMount() {
fetch("https://pokeapi.co/api/v2/pokemon/")
.then((res)=> res.json())
.then((response)=> {
this.setState({
isLoading: false,
dataSource: response
})
console.log(response)
})
}
render() {
const showIndicator = this.state.isLoading == true ? <ActivityIndicator size="large" color="#0000ff" /> : null;
return(
<View style={{marginTop:100}}>
<View>{showIndicator}</View>
<FlatList data={this.state.dataSource.results}
renderItem={({item})=> {
console.log("item is item",item);
return(
<View>
<Text>{item.name}</Text>
</View>
)
}}/>
<Button onPress={()=> this.props.navigation.navigate("About")} title="Go to about"/>
</View>
)
}
}
export default Home;
希望这可以帮助!