最平坦的获取数组现在显示本机反应

时间:2018-12-14 16:54:12

标签: api async-await react-native-ios fetch-api react-native-flatlist

我没有从我的api数组中获取任何项目,并且没有填充到最扁平的项目中。我想创建一个排行榜,从我的api(数组)中提取用户名和积分。

下面的

是我为项目准备的,我确实将api取出了。我不知道这是怎么回事。

我正在使用async / await提取方法。

export default class HomeScreen extends Component {
constructor(props) {
    super(props);
    this.state = {
        data: [],}
}

async getLeaderBoard() {
    try {
        let response = await fetch('api_here', {
            method: 'GET',
            headers: {
                Accept: 'application/json',
                Authorization: 'Bearer + token'

            },
        });
        let responseJson = await response.json();
        return responseJson;
    } catch (error) {
        console.log('There has been a problem with your fetch operation: ' + error.message);
        throw error;
    };
}


componentDidMount() {
    this.getLeaderBoard()
}

renderItem = ({ item, index }) => {
    console.log(item.title);
    this._carousel.triggerRenderingHack();
    return (
        <Image style={{ width: 100, height: 200, borderRadius: 12, marginTop: 10 }} source={{ uri: item }} />
    );
}

render() {
    return (<View style={{ width: Dimensions.get('window').width, height: Dimensions.get('window').height, alignItems: 'center' }}>


        <View style={{ flex: 1, flexDirection: 'column' }}>
            <Text style={{ marginTop: 50 }}>LEADER BOARD</Text>
        </View>
        <FlatList
            data={this.state.getLeaderBoard}
            keyExtractor={(x, i) => i}
            renderItem={({ item }) =>
            <Text>
                {`${item.name} ${item.points}`}
            </Text>
            }>
        </FlatList>
    </View>)
}

}

1 个答案:

答案 0 :(得分:0)

问题在于您没有将数据存储在任何地方。您的方法getLeaderBoard不是状态的一部分,您误解了。您应该执行以下操作:

您的方法getLeaderBoard

async getLeaderBoard() {
   try {
       let response = await fetch('api_here', {
           method: 'GET',
           headers: {
               Accept: 'application/json',
               Authorization: 'Bearer + token'

           },
       });
       let responseJson = await response.json();
       this.setState({data : responseJson}) // Store the API response on the state
   } catch (error) {
       console.log('There has been a problem with your fetch operation: ' + error.message);
       throw error;
   };
}

您的渲染方法:

render() {
   return (<View style={{ width: Dimensions.get('window').width, height: Dimensions.get('window').height, alignItems: 'center' }}>


       <View style={{ flex: 1, flexDirection: 'column' }}>
           <Text style={{ marginTop: 50 }}>LEADER BOARD</Text>
       </View>
       <FlatList
           data={this.state.data}  // The data is passed to the list
           keyExtractor={(x, i) => i}
           renderItem={({ item }) =>
           <Text>
               {`${item.name} ${item.points}`}
           </Text>
           }>
       </FlatList>
   </View>)
}

我建议您阅读State and Lifecycle docs