在本地响应中用json数据填充平面列表,这不可能吗?

时间:2018-09-17 21:42:41

标签: json react-native react-native-flatlist

我在本机反应方面非常陌生,刚开始了解它。玩弄从我的虚拟api获取json数据并用它填充视图。

当前使用的是平面列表,效果很好!当我给它一个非常基本的json数组项时,它不起作用。

这是基本json数据数组的外观:

[{"Note 1": "This is note number 1."}, {"Note 2": "This is note number 2."}, {"Note 3": "This is note number 3."}]

这是我正在玩的非常临时和基本的代码:

 render() {
        let apiData = fetch("address of my api which is not relevant, it works")
            .then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson);
                return responseJson;
            })
            .catch((error) => {
                console.error(error);
            });
        console.log(apiData);
        return (
            <View style={styles.notesContainer}>
                <FlatList
                    data={apiData}
                    renderItem={({ item }) => <Text style={styles.item}>{item.key}</Text>}
                />
            </View>
        );
    }

json数组非常简单,仅包含3个对象。如果我创建了一个随机物品列表(如文档中“ Key:value”所述,则列表有效。

真的可以,我需要以某种方式处理基本的json数组,然后才能将其设置为平板列表的数据源吗?

1 个答案:

答案 0 :(得分:2)

使用componentDidMount从API提取数据,并使用state存储apiData。

因此您的代码将类似于:

   constructor () {
    super(props);
    state = {
         apiData:[]
    };

  }

 componentDidMount =()=>{
        fetch("address of my api which is not relevant, it works")
            .then((response) => response.json())
            .then((responseJson) => {
                console.log(responseJson);
                this.setState(apiData);
            })
            .catch((error) => {
                console.error(error);
            });

  } 

  render() {
        return (
            <View style={styles.notesContainer}>
                <FlatList
                    data={this.state.apiData}
                    renderItem={({ item }) => <Text style={styles.item}>{item.key}</Text>}
                />
            </View>
        );
    }