Как я могу показать данные Json с помощью flatList? - PullRequest
0 голосов
/ 26 апреля 2019

Я хочу показать эти json данные по FlatList, но я не вижу никакого результата.Я видел все подобные вопросы, но другие вопросы не решили мою проблему.

Данные Json (console.log(responseJson);):

1: {title: "Shirt", type: "one", cost: "3500", cat: null, end: "1"}
2: {title: "Shirt", type: "two", cost: "4000", cat: null, end: "0"}
3: {title: "Shirt", type: "three", cost: "7000", cat: null, end: "2"}

коды:

constructor(props) {
    super(props);
    this.state = {
        dataSource: null,
        isLoading: true,
    }
}

componentDidMount() {
    fetch('products.php', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-type': 'application/json'
        },
        body: JSON.stringify({
            id: 4
        })
    })
    .then((response) => response.json())
    .then((responseJson) => {
            console.log(responseJson);
            this.setState({
                dataSource: responseJson,
                isLoading: false,
            });
        }    
    })
    .done();

}

return (
    <Container style={{ backgroundColor: '#f5f5f5' }}>
        <Header>
            <Title>{this.props.navigation.getParam('title')}</Title>
        </Header>
        <View style={{ margin: 10, borderRadius: 3 }}>
            <FlatList
                data={this.state.dataSource}
                renderItem={({ item }) =>
                    <View>
                        <Text>{item.title} - {item.type}</Text>
                        <Text>{item.cost.replace(/<(?:.|\n)*?>/gm, '')}$</Text>
                        <TouchableOpacity onPress={this.decrementCount} activeOpacity={0.5}>
                            <AntDesign name="minus" size={15} style={{ color: '#fff' }} />
                        </TouchableOpacity>
                        <Text>{this.state.quantity}</Text>
                        <TouchableOpacity onPress={this.incrementCount} activeOpacity={0.5}>
                            <AntDesign name="plus" size={15} style={{ color: '#fff' }} />
                        </TouchableOpacity>
                    </View>
                }
            />
        </View>
    </Container>
)

1 Ответ

0 голосов
/ 26 апреля 2019

Вам нужен массив в FlatList данных, но ваш json является объектом.

Попробуйте это

<FlatList
    data={[
        {title: "Shirt", type: "one", cost: "3500", cat: null, end: "1"},
        {title: "Shirt", type: "two", cost: "4000", cat: null, end: "0"},
        {title: "Shirt", type: "three", cost: "7000", cat: null, end: "2"},
    ]
...
...