невозможно перечислить данные, используя плоский список - PullRequest
0 голосов
/ 23 января 2019

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

, поэтому в компоненте flatlist я подозреваюпроблема заключается в renderItem prop.

state = {bookData:[]}

  componentWillMount ()
  {
axios.get('https://udhishtabharata.com/appsupport/alanwattsapp/services/ list/book///id')
       .then(response => this.setState({bookData: response.data}))
   }
 renderdata(){
   {console.log(this.state.bookData)}
 }

 render(){
     return (
      <View style={styles.viewStyles}>
      <View style={styles.statusBarStyle} />
      <Header headerText='Books' />
      {this.renderdata()}
      <List>
        <FlatList>
            data={this.state.bookData}

            renderItem={({item})=> (
              <ListItem 
                roundAvatar
                title={item.title}

              />
            )}
        </FlatList>
      </List>

  </View>
);
}
}

, и мой ответ:

[
  {
    "id":"32",
    "title":"Become What You Are",
    "subtitle":"",
    "photo":"/files/pictures/book/32-5.jpg",
    "url":"https://www.amazon.com/Become-What-You-Alan-Watts/dp/1570629404",
    "metakeywords":"Alan Watts Book: Become What You Are",
    "metadescr":"The book Become what you are published in 1957 presents Alan Watts’ meditations and reflections on the dilemma of capturing the true self. ",
    "metatitle":"Alan Watts Book: Become What You Are",
    "doa":"2018-11-20 12:13:31",
    "dou":"2018-11-20 12:31:39",
    "descr":"<div>The book 'Become what you are' published in 1957 presents Alan Watts’ meditations and reflections on the dilemma of capturing the true self. Become what you are exposes the playfulness and intelligence of thought and simplicity of language that has made him famous as an exponent of Eastern thoughts for Westerners. <br></div><div><br></div><div>\r\nIn the book, he discusses various philosophical ideas and offers practical wisdom of the life of human beings. He rejects the thought of ego which is to be avoided but is unavoidable in every aspect of life. Changing the nature of life is the root of this work. It gives a lively effect on your mind and examines how the reality works in several aspects and variants of life situations. It gives the basic knowledge on Zen and Tao from which the detailed idea of wisdom is understood. The whole concept revolves around seeing life as it is which is the taoist notion of joyful living.</div>",
    "views":"0",
    "outboundlinkclick":"0",
    "urlname":"become_what_you_are",
    "status":"A",
    "customer_name":"",
    "customer_photo":""
  },
  {
    "id":"35",
    "title":"The Way of Zen",
    "subtitle":"",
    "photo":"/files/pictures/book/35-2.jpg",
    "url":"https://www.amazon.com/Way-Zen-Alan-W-Watts/dp/0375705104",
    "metakeywords":"",
    "metadescr":"",
    "metatitle":"",
    "doa":"2018-11-20 12:39:57",
    "dou":"2018-11-20 12:50:00",
    "descr":"<div>The Way of Zen is a clear-cut presentation of Zen Buddhism which is published in 1957. Alan Watts examines and explains the concepts, notions and principles of ancient religion to the Western world. The book gives a complete clarification of Zen Buddhism which has a massive difference from the Southern Indian Buddhism.</div><div>The Way of Zen is completely a non-fiction book, which is divided in to two sections. The first part deals with historical development of Zen Buddhism and second part gives a clear idea on the principles of the same. Alan traces the birth of Zen Buddhism in relation to Chinese Taoism and Mahayana Buddhism. The work also introduces a variety of philosophical concepts such as The Middle Way, anatman and wuwei. Watts, through The Way of Zen gives a clarity of thought on the ways of liberation followed by Zen Buddhism and how it is easily adapted in our lives to lead a quality life.</div>",
    "views":"0",
    "outboundlinkclick":"0",
    "urlname":"the_way_of_zen",
    "status":"A",
    "customer_name":"",
    "customer_photo":""
  }
]

мне нужно, чтобы список отображался на экране.любая помощь приветствуется

Ответы [ 2 ]

0 голосов
/ 23 января 2019

При попытке сделать заказ в вашем коде я обнаружил некоторые ошибки или неправильное использование

state = {
    bookData:[]
}

componentDidMount(){
    axios.get('https://udhishtabharata.com/appsupport/alanwattsapp/services/ list/book///id')
    .then(response => this.setState({bookData: response.data}))
}

render(){
    return (
        <View style={styles.viewStyles}>
            <View style={styles.statusBarStyle} />
            <FlatList
                data={this.state.bookData}
                renderItem={({item})=> 
                    <ListItem 
                    roundAvatar
                    title={item.title}
                    />
                }
                extraData={this.state.bookData}
                keyExtractor={(item) => item.id}
                ListHeaderComponent={<Header headerText='Books' />}
            />
        </View>
    );
}
  • Предпочитаю componentDidMount() вместо componentWillMount() как место, где можно получить данные и установить ваше состояние
  • Вы можете легко использовать просто FlatList
  • Осторожно, как вы объявляете Flatlist (вы неправильно закрыли тег >)
  • Pass FlatList a ListHeaderComponent реквизит, если вы хотите, чтобы он прокручивался с вашим списком
0 голосов
/ 23 января 2019

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

 state = {bookData:[]}

  componentWillMount ()
  {
      axios.get('https://udhishtabharata.com/appsupport/alanwattsapp/services/ list/book///id')
       .then(response => this.setState({bookData: response.data}))
  }

 renderdata(){
   {console.log(this.state.bookData)}
 }

renderItems = ({ item, index }) => {
    return (
        <View key={index}>
                <TouchableOpacity>
                    <Image source={} />
                </TouchableOpacity> 
        </View>
    )
};

_keyExtractor = (item, index) => item.id;

 render(){
     return (
      <View style={styles.viewStyles}>
      <View style={styles.statusBarStyle} />
      <Header headerText='Books' />
        <FlatList
            data={this.state.bookData}
            keyExtractor={this._keyExtractor}
            renderItem={this.renderItems}
              />

  </View>
);
}

Выполните стилизацию в функции renderItem В функции renderItem вы получаете один за другим объект, поэтому в соответствии с вашим дизайном вносите изменения в стили и отображаете данные

...