有没有更有效的方法使用 axios 从 API 获取数据?(React.js & node。HSK



在这个实现中,代码运行并实现了我试图做的目的-使用axios在https://jsonplaceholder.typicode.com上获取虚拟API,然后将其显示在屏幕上。然而,我觉得我的代码可以重构,变得更有效率。目前,我有四个useState常量(一个用于对象中的每个属性),它们在获取时进行设置/更新。我试图将CurrentFetchCurrentFetch2CurrentFetch3CurrentFetch4常量合并到单个useState({})对象中,但React在这里给我使用对象的错误。什么好主意吗?

下面是我的代码:
import React, { useState } from "react";
import "./App.css";
import axios from "axios";
function App() {
const [fetchCount, setFetchCount] = useState(1);
const [currentFetch, setCurrentFetch] = useState([]);
const [currentFetch2, setCurrentFetch2] = useState([]);
const [currentFetch3, setCurrentFetch3] = useState([]);
const [currentFetch4, setCurrentFetch4] = useState([]);

const HandleFetchApi = async () => {
axios
.get(`https://jsonplaceholder.typicode.com/todos/${fetchCount}`)
.then((response) => {
let data = response.data;
setCurrentFetch(data.userId);
setCurrentFetch2(data.id);
setCurrentFetch3(data.title);
setCurrentFetch4(data.completed);
setFetchCount(fetchCount + 1);
})
.catch((error) => {
console.log(error);
});
};
return (
<div className="App">
<h1>Testing API Fetch from Dummy Api</h1>
<button onClick={HandleFetchApi}>
Click to fetch record #{fetchCount}
</button>
<h2>user id: {currentFetch}</h2>
<h2>id: {currentFetch2}</h2>
<h2>title: {currentFetch3}</h2>
<h2>completed: {currentFetch4.toString()}</h2>
<br />
<h5>from: https://jsonplaceholder.typicode.com/</h5>
</div>
);
}
export default App;

更好的版本:

import React, { useState } from "react";
import "./App.css";
import axios from "axios";
function App() {
const [fetchCount, setFetchCount] = useState(1);
const [currentFetch, setCurrentFetch] = useState({
userId: '',
id: '',
title: '',
completed: ''
});

const HandleFetchApi = async () => {
axios
.get(`https://jsonplaceholder.typicode.com/todos/${fetchCount}`)
.then((response) => {
const { userId, id, title, completed } = response.data;
setCurrentFetch({...currentFetch, ...{userId, id, title, completed}});
setFetchCount(fetchCount + 1);
})
.catch((error) => {
console.log(error);
});
};
return (
<div className="App">
<h1>Testing API Fetch from Dummy Api</h1>
<button onClick={HandleFetchApi}>
Click to fetch record #{fetchCount}
</button>
<h2>user id: {currentFetch.userId}</h2>
<h2>id: {currentFetch.id}</h2>
<h2>title: {currentFetch.title}</h2>
<h2>completed: {currentFetch.completed.toString()}</h2>
<br />
<h5>from: https://jsonplaceholder.typicode.com/</h5>
</div>
);
}
export default App;

Happy Coding:)

最新更新