我工作的一個非常簡單的反應,本機應用程序,我在搜索欄中鍵入藝術家的名稱,顯示Spotify的API查詢的結果,並顯示藝術家,我得到了使用Spotify的的Flatlist API。無法在FlatList
我有2個文件我App.js,做實現了API調用的渲染和fetcher.js。
但我無法去出現在列表中,我無法設置藝術家的狀態。
App.js
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 }
/>
<Text> {this.state.artists} </Text>
</View>
);
}
makeQuery = debounce(query => {
searchArtist(query)
.then((artists) => {
this.setState({
artists: this.state.artists,
});
//console.log(artists)
})
.catch((error) => {
throw error;
});
}, 400);
}
const styles = StyleSheet.create({
container: {
paddingTop: 64,
flex: 1,
backgroundColor: colors.white,
},
searchBox: {
height: 40,
borderColor: colors.black,
borderWidth: 2,
margin: 16,
paddingLeft: 10,
fontWeight: '800',
},
row: {
flex: 1,
margin: 30,
alignSelf: 'stretch',
justifyContent: 'center',
},
});
fetch.js
export function searchArtist(query) {
const ClientOAuth2 = require('client-oauth2')
console.log("Query : " + query)
const spotifyAuth = new ClientOAuth2({
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
accessTokenUri: 'https://accounts.spotify.com/api/token',
authorizationUri: 'https://accounts.spotify.com/authorize',
scopes: []
})
spotifyAuth.credentials.getToken()
.then((user) => user.accessToken)
.then((token) => getQuery(token, query))
.then((result) => {
console.log(result) // No list :(
return result
});
}
function getQuery(token, query) {
console.log("Query2 : " + query)
const settings = {
"url": `https://api.spotify.com/v1/search?q=${ query }&type=artist`,
"method": "GET",
"headers": {
"authorization": "Bearer " + token,
"cache-control": "no-cache",
}
}
fetch(settings)
.then((res) => res.json())
.then(data => {
const artists = data.artists ? data.artists.items : [];
console.log(artists) // I get the list in the debbuger
return artists;
});
}
謝謝您的幫助。
謝謝你的回答!現在我可以在我的「makeQuery」例程中獲得藝術家列表,但是this.state.artists似乎沒有設置。我嘗試了FlatList的不同實現,但不可能顯示任何內容。你能幫我@andrii嗎? – mandok
看來你是不更新數據的狀態,你'makeQuery'得到 '。然後((藝術家)=> { this.setState({ 藝術家:this.state.artists, }); // 控制檯.log(artists) })' 試試這個: 'this.setState({artists});' –
是的,就是這樣!非常感謝 – mandok