2017-09-16 129 views
0

我正在一个非常简单的反应原生应用程序,我在搜索框中键入艺术家的名字,从spotify API中检索艺术家列表,并在FlatList中显示此列表零件。SetState似乎并没有更新

我设法得到艺术家列表,我想将它保存在本地状态,以便将它传递给FlatList组件。

列表对象看起来像这样:[{...},{...},{...},{...}]

但它似乎没有工作,我认为我的状态没有更新,我不知道我做错了什么。

import React, { Component } from 'react'; 
import { 
    AppRegistry, 
    StyleSheet, 
    Text, 
    View, 
    FlatList, 
    StatusBar, 
    TextInput, 
} from 'react-native'; 

import colors from './utils/colors'; 
import { List, ListItem, SearchBar } from 'react-native-elements'; 
import { searchArtist } from './utils/fetcher'; 
import { debounce } from 'lodash'; 


export default class spotilist extends Component { 
    constructor(props) { 
    super(props); 

    this.state = { 
     loading: false, 
     data: [], 
     query: '', 
     artists: [], 
     error: null, 
     refreshing: false, 
    }; 
    } 


    render() { 
    return (

     <View style={ styles.container }> 
     <StatusBar barStyle="light-content" /> 
     <TextInput style={ styles.searchBox } 
      value={this.state.value} 
      onChangeText={ this.makeQuery } 
     /> 
     <List> 
      <FlatList 
      data={this.state.artists} 
      //renderItem={({item}) => <Text>{item.name}</Text>} 
      /> 
     </List> 

     // { 
     // this.state.artists.map(artist => { 
     //  return (
     //  <Text key={artist.id}>{artist.name}</Text> 
     // ) 
     // }) 
     // } 

     </View> 
    ); 
    } 

    makeQuery = debounce(query => { 
    searchArtist(query) 
     .then((artists) => { 
     console.log(artists); // I have the list 
     this.setState({ 
      artists: this.state.artists, 
     }); 
     }) 
     .catch((error) => { 
     throw error; 
     }); 
    }, 400); 

} 

谢谢您的帮助。

UPDATE

我用这个没有成功也试过:

<List> 
     <FlatList 
     data={this.state.artists} 
     renderItem={({ item }) => (
      <ListItem 
      roundAvatar 
      title={item.name} 
      avatar={{ uri: item.images[0].url }} 
      /> 
     )} 
     /> 
    </List> 
+0

是否在为'renderItem'添加道具之后还没有渲染? – bennygenel

+0

@bennygenel是的,当我添加它时不工作。 – mandok

+0

你在哪里调用'makeQuery'方法? –

回答

2

在您需要设置从服务器一样的响应makeQuery功能..

makeQuery = debounce(query => { 
searchArtist(query) 
    .then((artists) => { 
    console.log(artists); // I have the list 
    this.setState({ 
     artists: artists, //Here is the change 
    }); 
    }) 
    .catch((error) => { 
    throw error; 
    }); 
}, 400);