[英]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.