Javascript 在按钮按下时从API重新蚀刻反应本机
我正在尝试在React Native中单击按钮重新获取新数据。怎么做 这是我当前的代码,它不会在点击按钮时获取新内容,而是不会发生任何事情 我已经完成了,直到它从API中获取内容,但无法在按钮单击时实现刷新,因为Flatlist并没有一次又一次地加载 提前谢谢Javascript 在按钮按下时从API重新蚀刻反应本机,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我正在尝试在React Native中单击按钮重新获取新数据。怎么做 这是我当前的代码,它不会在点击按钮时获取新内容,而是不会发生任何事情 我已经完成了,直到它从API中获取内容,但无法在按钮单击时实现刷新,因为Flatlist并没有一次又一次地加载 提前谢谢 import React, { useEffect, useState } from 'react'; import { ActivityIndicator, FlatList, StyleSheet, View, Text, Butto
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="Give useEffect
dependency on which it will trigger when the button will be clicked.
Add new state which will toggle when the button will be clicked:
const App: () => React$Node = () => {
const [isLoading, setLoading] = useState(true);
const [data, setData] = useState([]);
const [refetch, setRefetch] = useState(false); // <= this
import React,{useffect,useState}来自“React”;
从“react native”导入{ActivityIndicator,FlatList,样式表,视图,文本,按钮};
进口{
颜色
}来自“react native/Libraries/NewAppScreen”;
常量应用程序:()=>React$Node=()=>{
const[isLoading,setLoading]=useState(true);
const[data,setData]=useState([]);
useffect(()=>{
取('https://exampleapi.dev/')
.then((response)=>response.json())
.然后((json)=>setData(json))
.catch((错误)=>console.error(错误))
.最后(()=>setLoading(false));
}, []);
返回(
{正在加载?:(
id}
renderItem={({item})=>(
{item.content}
)}
/>
)}
给出单击按钮时将触发的useffect
依赖项
添加单击按钮时将切换的新状态:
useEffect(() => {
fetch("https://exampleapi.dev/")
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, [refetch]);
最后,只需切换refetch
的状态:
->创建func从API获取数据,如:
->当点击按钮时,只需呼叫:
你救了我。非常感谢。欢迎光临,快乐编码。:)
<Button
title="-> Create func to getData from API like:
useEffect(() => {
getData()
}, []);
const getData = ()=>{
fetch('https://exampleapi.dev/')
.then((response) => response.json())
.then((json) => setData(json))
.catch((error) => console.error(error))
.finally(() => setLoading(false))
}