У меня проблема с Flatlist, Мне нужно отобразить данные ответа из API в Flatlist, но это не работает! но когда я устанавливаю статические данные, все работает нормально! и когда я регистрирую {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.info(responseJson);
// console.info(responseJson.city.name);
};
await fetch(req)
.then(response => response.json())
.then(responseJson =>
this.setState({ isLoading: false, dataSource: responseJson }, () =>
callback(responseJson)
)
)
.catch(error => console.info(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.info(this.state.dataSource.city.name)} // I get the City name
<FlatList
data = {this.state.dataSource}
renderItem = {({ item }) => (
<Text>
{item.message}, {item.city.name}
{console.info(item)} // NO Output
</Text>
)}
keyExtractor = {(item, index) => index}
/>
</View>
</ScrollView>
);
}
}
Добавьте реквизит extraData в FlatList. extraData используется для повторного рендеринга FlatList. extraData
Может, это тебе поможет.
<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.info(error));
вам также нужно изменить свою логику для значков в методе рендеринга:
const icon =
dataSource[0].list[0].main.temp <= 20
? require("./assets/cloudySun.png")
: require("./assets/sunny.png");
не могли бы вы поделиться своим ответом?
это происходит потому, что FlatList ожидает массив и ответ, которые вы получаете и храните в this. state.dataSource - это объект. Преобразуйте этот объект или ответ в массив и передайте его в this.state.dataSource. Может это работает
Я действительно так делаю, сохраняю ответ в таком состоянии, как это источник данных: [], так?
Я обновил свой ответ. пожалуйста, проверь это. возможно это решит вашу проблему.
спасибо, чувак, можешь проверить здесь stackoverflow.com/questions/53838539/…?
Это работает, когда я устанавливаю реквизиты данных Flatlist на ответ массива, такого как этот data = {this.state.dataSource.list}, потому что они будут их зацикливать для рендеринга, я думаю, но теперь он работает, если у вас есть какие-либо идеи, кроме этого, скажите мне, братан!