简体   繁体   English

用 json 数据填充平面列表,在本机反应中,不可能?

[英]Populating a flatlist with json data, in react native, not possible?

I'm very new at react native, just starting to get the hang of it.我对本机反应很陌生,刚刚开始掌握它。 Playing around with fetching json data from my dummy api and populating views with it.从我的虚拟 api 中获取 json 数据并用它填充视图。

Currently using a flatlist, which works fine!目前使用的是平面列表,效果很好! Except it doesn't work when I give it a very basic json array of items.除了当我给它一个非常基本的 json 项目数组时它不起作用。

This is how the basic json data array looks:这是基本的 json 数据数组的外观:

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

This is my very temporary and basic code I'm playing around with:这是我正在使用的非常临时和基本的代码:

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

The json array is very simple and just contains 3 objects. json 数组非常简单,只包含 3 个对象。 If I create a list of random stuff (as noted in the documentation with "Key: value", the flatlist works fine.如果我创建了一个随机内容列表(如“键:值”文档中所述,平面列表可以正常工作。

Can it really be true I need to handle a basic json array in some fashion before I can set is as a data source for a flatlist?在将 is 设置为 flatlist 的数据源之前,我真的需要以某种方式处理基本的 json 数组吗?

Use componentDidMount for fetching data from API and use state to store apiData.使用componentDidMount从 API 获取数据并使用 state 存储 apiData。

So your code will be like:所以你的代码会是这样的:

   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: responseJson});
            })
            .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>
        );
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM