我正在尝试使用axios获取api并将其设置在我的App.js文件中的状态
import React, { useEffect, useState } from "react";
import "./App.css";
import axios from "axios";
import UserDetails from "./user/userDetails";
function App() {
useEffect(() => {}, []);
const [userDetails, setUserDetails] = useState([]);
const getUser = async () => {
try {
return await
axios.get("https://randomuser.me/api").then((response) => {
if (response.data.results) {
setUserDetails(response.data.results);
}
});
} catch (error) {}
};
getUser();
console.log("!!!!!!!!!!!!!!!!!", userDetails);
return <>{<UserDetails data={userDetails} />}</>;
}
export default App;
我能够从getUser函数中获得响应,但无法在userDetails中设置此实现中的错误
在useEffect内部调用getUser函数
import React,{useEffect,useState} from 'react'
import './App.css';
import axios from "axios";
import UserDetails from './user/userDetails';
function App() {
const [userDetails,setUserDetails]=useState([])
useEffect(() => {
getUser();
},[])
const getUser=async()=>{
try {
return await axios.get('https://randomuser.me/api').then(response => {
if(response.data.results){
setUserDetails(response.data.results);
}
});
} catch (error) {
console.log('ERROR',error);
}
}
return <UserDetails data={userDetails}/>
}
export default App;
你可以尝试调用这个函数getUser();在使用效果中时间是起作用的
将getUser
函数移动到useEffect
钩子内,并使用fetchUserDetails
函数调用。还使用来自响应的实际数据更新了setUserDetails
函数。
import React, { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios';
import UserDetails from './user/userDetails';
function App() {
const [userDetails, setUserDetails] = useState([]);
useEffect(() => {
const fetchUserDetails = async () => {
try {
const response = await axios.get('https://randomuser.me/api');
const data = response.data.results;
setUserDetails(data);
} catch (error) {
console.error(error);
}
};
fetchUserDetails();
}, []);
console.log('!!!!!!!!!!!!!!!!!', userDetails);
return (
<>
<UserDetails data={userDetails} />
</>
);
}
export default App;