首页 > 解决方案 > 在 React Native 中按下按钮时从 API 重新获取

问题描述

我正在尝试在 React Native 中的 Button Click 上重新获取新数据。怎么做?

这是我当前的代码,它没有在 Button Click 上获取新内容,而是什么也没发生。

我已经完成了,直到它从 API 获取内容但无法在按钮单击时实现刷新,因为 Flatlist 不会一次又一次地加载。

提前致谢。

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, FlatList, StyleSheet, View, Text, Button } from 'react-native';

import {
  Colors
} from 'react-native/Libraries/NewAppScreen';


const App: () => React$Node = () => {

  
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);


  useEffect(() => {
    fetch('https://exampleapi.dev/')
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, []);


  return (
    <>
    <View style={styles.container}>
      {isLoading ? <ActivityIndicator/> : (
        <FlatList
          data={data}
          keyExtractor={({ id }, index) => id}
          renderItem={({ item }) => (
            <Text style={styles.content}>{item.content}</Text>
          )}
        />
      )}
      
    </View>
     <View style={styles.buttonBottom}> 
    <Button
        title=" Refresh"
        onPress={() => this.FlatList}
        style={styles.buttonShare}
        color="#66BB6A" />
     </View>       
    </>
    
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'space-between',
    backgroundColor: '#1b262c',
    padding: 30,
    flexDirection:'row',
    alignItems:'center'
  },
  FlatList: {
    backgroundColor: Colors.aquamarine,
  },
  content: {
    fontSize: 22,
    textAlign: 'left',
    color: '#bbe1fa'
  },
  buttonBottom: {
    fontSize: 22,
    padding: 10,
    backgroundColor: '#1b262c',
  }
});

export default App;

标签: javascriptreactjsreact-native

解决方案


useEffect指定单击按钮时将触发的依赖项。

添加将在单击按钮时切换的新状态:

const App: () => React$Node = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const [refetch, setRefetch] = useState(false); // <= this

现在设置refetch为依赖项useEffect

useEffect(() => {
    fetch("https://exampleapi.dev/")
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, [refetch]);

最后,只需切换状态refetch

<Button
          title=" Refresh"
          onPress={() => setRefetch(!refetch)}
          style={styles.buttonShare}
          color="#66BB6A"
        />

最终更改应如下所示:

import React, { useEffect, useState } from "react";
import {
  ActivityIndicator,
  FlatList,
  StyleSheet,
  View,
  Text,
  Button,
} from "react-native";

import { Colors } from "react-native/Libraries/NewAppScreen";

const App: () => React$Node = () => {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const [refetch, setRefetch] = useState(false);

  useEffect(() => {
    fetch("https://exampleapi.dev/")
      .then((response) => response.json())
      .then((json) => setData(json))
      .catch((error) => console.error(error))
      .finally(() => setLoading(false));
  }, [refetch]);

  return (
    <>
      <View style={styles.container}>
        {isLoading ? (
          <ActivityIndicator />
        ) : (
          <FlatList
            data={data}
            keyExtractor={({ id }, index) => id}
            renderItem={({ item }) => (
              <Text style={styles.content}>{item.content}</Text>
            )}
          />
        )}
      </View>
      <View style={styles.buttonBottom}>
        <Button
          title=" Refresh"
          onPress={() => setRefetch(!refetch)}
          style={styles.buttonShare}
          color="#66BB6A"
        />
      </View>
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "space-between",
    backgroundColor: "#1b262c",
    padding: 30,
    flexDirection: "row",
    alignItems: "center",
  },
  FlatList: {
    backgroundColor: Colors.aquamarine,
  },
  content: {
    fontSize: 22,
    textAlign: "left",
    color: "#bbe1fa",
  },
  buttonBottom: {
    fontSize: 22,
    padding: 10,
    backgroundColor: "#1b262c",
  },
});

export default App;

推荐阅读