React native - Инвариантное нарушение - попытался получить фрейм для индекса вне диапазона - PullRequest
0 голосов
/ 26 апреля 2020

Я пытался искать другие сообщения и форумы для решения этой ошибки. Однако, либо никто не решил эти проблемы, либо проблемы на самом деле не делают то же самое, что я делаю. Я получаю сообщение об ошибке «Инвариантное нарушение - попытался получить кадр для индекса вне диапазона». Это происходит, когда я пытаюсь ввести данные в плоский список из API poke. Пожалуйста, смотрите код ниже.

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;

1 Ответ

1 голос
/ 26 апреля 2020

То, что вы делаете неправильно, вы отправляете 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;

enter image description here

Надеюсь, это поможет!

...