简体   繁体   English

React Native 没有从 API 调用中获取最新数据

[英]React Native is Not fetching the latest data from API call

I sicerely Apologies if this has been asked before.如果以前有人问过这个问题,我深表歉意。 I am a bit new to react native and react in general.我对本机反应和一般反应有点陌生。

my react nativee code is not fetcing the latest data see the code for the list component below I would deeply appreciate it if you can tell me why this is happening and how to make it pick the latest data我的反应原生代码没有获取最新数据请参阅下面列表组件的代码如果您能告诉我为什么会发生这种情况以及如何使其选择最新数据,我将不胜感激

import React, { Component } from "react";
import {
  FlatList,
  Text,
  View,
  StyleSheet,
  ScrollView,
  ActivityIndicator
} from "react-native";
import Constants from "expo-constants";
import { createStackNavigator } from "@react-navigation/stack";
import { toCommaAmount } from "./utilities";

const Stack = createStackNavigator();

function MyStack() {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Home" component={ExpenseList} />
      <Stack.Screen name="NewTransaction" component={ExpenseForm} />
    </Stack.Navigator>
  );
}

function Item({ title }) {
  return (
    <View style={styles.item}>
      <Text style={styles.title}>{title}</Text>
    </View>
  );
}

class ExpenseList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      dataSource: null
    };
  }

  componentDidMount() {
    return fetch("https://example.com/expense/api/get_all.php")
      .then(response => response.json())
      .then(responseJson => {
        this.setState({
          isLoading: false,
          dataSource: responseJson.items
        });
      })

      .catch(error => console.log(error));
  }

  render() {
    if (this.state.isLoading) {
      return (
        <View style={styles.container}>
          <ActivityIndicator />
        </View>
      );
    } else {
      let myExpenses = this.state.dataSource.map((val, key) => {
        return (
          <View key={key} style={styles.item}>
            <Text>
              {val.title} {toCommaAmount(val.amount)}
            </Text>
            <Text>{val.date_time}</Text>
          </View>
        );
      });

      return <View style={styles.container}>{myExpenses}</View>;
    }
  }
}

export default ExpenseList;

ComponentDidMount is a void function. ComponentDidMount 是一个 void function。 I assume you have this problem because you try to return the result of the fetch execution.我假设你有这个问题,因为你试图返回 fetch 执行的结果。

Can you remove your api call out of componentDidMount(), because it gets invoked only once.您能否从 componentDidMount() 中删除您的 api 调用,因为它只被调用一次。 Rename it to getRealData() and attach it to a button click.将其重命名为 getRealData() 并将其附加到按钮单击上。 So every click on button will being up latest data from backend.所以每次点击按钮都会从后端获取最新数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM