【问题标题】:How Can I show Json data by flatList?如何通过 flatList 显示 Json 数据?
【发布时间】:2019-04-26 14:29:29
【问题描述】:

我想通过FlatList 显示这个json 数据,但我看不到任何结果。我看到了所有这样的问题,但其他问题没有解决我的问题。

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>
)

【问题讨论】:

  • 这些对象应该在一个数组中......你确定你得到数组
  • @MAhipalSingh 你可以在上面的代码中看到我的console.log ..
  • 你的代码看起来很完美,所以我建议你做一些测试,首先将响应中的json直接添加到FlatList数据的代码中。例如&lt;FlatList data={yourjson} ...。并检查它是否呈现并让我们知道
  • @Vencovsky 你说得对。我的 json 有问题。我应该删除数字..
  • 你可能有一个对象的属性是数字,而不是数组

标签: react-native react-native-flatlist


【解决方案1】:

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"},
    ]
...

【讨论】:

    猜你喜欢
    • 2019-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2015-12-08
    • 2017-08-22
    相关资源
    最近更新 更多