【问题标题】:How to render the response API with Flatlist in react native?如何在 react native 中使用 Flatlist 呈现响应 API?
【发布时间】:2023-04-01 02:07:02
【问题描述】:

我对平面列表有一些问题, 我需要在 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>
    );
  }
}

【问题讨论】:

    标签: javascript android reactjs react-native fetch


    【解决方案1】:

    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.log(error));
    

    您还必须更改渲染方法中图标的逻辑:

    const icon =
          dataSource[0].list[0].main.temp <= 20
            ? require("./assets/cloudySun.png")
            : require("./assets/sunny.png");
    

    【讨论】:

    • 当我将 Flatlist 的 Data 道具设置为像这样 data={this.state.dataSource.list} 这样的数组的响应时,这是有效的,因为它们会将它们循环到渲染我想,但如果你有任何想法,现在就可以了除此之外告诉我兄弟!
    • 您能分享一下您的回复吗?
    • 发生这种情况是因为 FlatList 需要一个数组和响应,您获取并存储在 this.state.dataSource 中的是一个对象。请转换数组中的这个对象或响应,并将其传递到 this.state.dataSource。也许它正在工作
    • 我真的在这样做,将响应存储在像这样的状态 dataSource: [],所以?
    • 我已经更新了我的答案。请检查一下。也许这会解决你的问题。
    猜你喜欢
    • 2019-06-17
    • 1970-01-01
    • 2021-03-25
    • 2021-12-17
    • 2019-03-17
    • 2020-06-20
    • 2021-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多