[英]How to render the response API with Flatlist in react native?
我對Flatlist有一些問題,我需要在Flatlist中呈現來自API的響應數據,但是它不起作用! 但是當我設置靜態數據時,它可以正常工作! 當我登錄{item}時,在“調試”中什么也沒有顯示! 我認為Flatlist的語法是正確的! 有人,您能幫我解決這個問題嗎?
我的代碼在這里
import React, { Component } from "react";
import {
StyleSheet,
Text,
View,
TextInput,
ScrollView,
Image,
ActivityIndicator,
FlatList,
ListItem
} from "react-native";
import Moment from "react-moment";
import Icon from "react-native-vector-icons/dist/FontAwesome";
export default class App extends Component {
constructor(props) {
super(props);
this.ApiKeyRef = "****";
this.watchPositionOpts = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 1000,
distanceFilter: 5
};
this.state = {
isLoading: true,
dataSource: [],
latitude: null,
longitude: null,
error: null
};
}
componentDidMount() {
this.watchId = navigator.geolocation.watchPosition(
this.watchPositionSuccess,
this.watchPositionFail,
this.watchPositionOpts
);
}
componentWillUnmount() {
navigator.geolocation.clearWatch(this.watchId);
navigator.geolocation.stopObserving();
}
watchPositionSuccess = position => {
this.setState(
{
latitude: position.coords.latitude,
longitude: position.coords.longitude,
error: null
},
() => this.fetchCallback()
);
};
watchPositionFail = err => {
this.setState({ error: err.message });
};
fetchCallback = async () => {
const { latitude, longitude } = this.state;
const req = `http://api.openweathermap.org/data/2.5/forecast?lat=${latitude}&lon=${longitude}&units=metric&appid=${
this.ApiKeyRef
}`;
const callback = responseJson => {
// console.log(responseJson);
// console.log(responseJson.city.name);
};
await fetch(req)
.then(response => response.json())
.then(responseJson =>
this.setState({ isLoading: false, dataSource: responseJson }, () =>
callback(responseJson)
)
)
.catch(error => console.log(error));
};
render() {
const { dataSource } = this.state;
if (this.state.isLoading) {
return (
<View style={{ flex: 1, padding: 20 }}>
<ActivityIndicator />
</View>
);
}
const icon =
dataSource.list[0].main.temp <= 20
? require("./assets/cloudySun.png")
: require("./assets/sunny.png");
return (
<ScrollView style={styles.container}>
<View style={styles.head}>
<Text style={styles.titleApp}>Weather App</Text>
</View>
<View style={styles.searchSection}>
<Icon
style={styles.searchIcon}
name="search"
size={15}
color="#333"
/>
<TextInput
style={styles.input}
placeholder="Find Your City.."
underlineColorAndroid="transparent"
/>
</View>
<View style={styles.details}>
{console.log(this.state.dataSource.city.name)} // I get the City name
<FlatList
data={this.state.dataSource}
renderItem={({ item }) => (
<Text>
{item.message}, {item.city.name}
{console.log(item)} // NO Output
</Text>
)}
keyExtractor={(item, index) => index}
/>
</View>
</ScrollView>
);
}
}
將extraData道具添加到FlatList。 extraData用於重新呈現FlatList。 而額外
也許會對您有幫助。
<FlatList
data={dataSource}
extraData={this.state} //for re-render the Flatlist data item
renderItem={({ item }) => (
<Text>
{item.message}, {item.city.name}
</Text>
)}
keyExtractor={(item, index) => index}
/>
將對象響應轉換為數組
await fetch(req)
.then(response => response.json())
.then(responseJson =>{
let data = [];
data.push(responseJson); //convert object response to array
this.setState({ isLoading: false, dataSource: data }, () =>
callback(data)
)}
)
.catch(error => console.log(error));
您還必須在render方法中更改圖標的邏輯:
const icon =
dataSource[0].list[0].main.temp <= 20
? require("./assets/cloudySun.png")
: require("./assets/sunny.png");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.