【发布时间】:2021-08-02 18:35:55
【问题描述】:
在这个实现中,代码运行并实现了我想要做的目的——使用 axios 获取https://jsonplaceholder.typicode.com 的虚拟 API,然后将其显示在屏幕上。但是,我觉得我的代码可以重构以提高效率。目前,我有四个 useState 常量(对象中的每个属性一个),它们在获取时设置/更新。我试图将 CurrentFetch CurrentFetch2 CurrentFetch3 CurrentFetch4 常量合并到一个 useState({})object 中,但是 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;
【问题讨论】:
-
这看起来像是有效的代码;你需要展示你重构它的尝试。 (
setTodo(response.data);就是你所需要的) -
您在使用单个对象时遇到了哪些错误?
-
当我尝试
setCurrentFetch(data)时出错:对象作为 React 子项无效(找到:带有键 {} 的对象)。如果您打算渲染一组子项,请改用数组。 -
你需要使用
<h2>user id: {currentFetch.id}</h2>然后,你试图完全按照错误所说的去做:渲染一个非 React 对象。这里:codesandbox.io/s/elated-dawn-66s6k?file=/src/App.js -
另外,
<h2>completed: {currentFetch.completed?.toString()}</h2>非常有帮助。?.在英语语义中是什么意思? @ChrisG
标签: javascript node.js reactjs axios