【问题标题】:Is there a more efficient way to fetch data from an API using axios? (React.js & node.Js)有没有更有效的方法来使用 axios 从 API 中获取数据? (React.js & node.Js)
【发布时间】: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 子项无效(找到:带有键 {} 的对象)。如果您打算渲染一组子项,请改用数组。
  • 你需要使用 &lt;h2&gt;user id: {currentFetch.id}&lt;/h2&gt; 然后,你试图完全按照错误所说的去做:渲染一个非 React 对象。这里:codesandbox.io/s/elated-dawn-66s6k?file=/src/App.js
  • 另外,&lt;h2&gt;completed: {currentFetch.completed?.toString()}&lt;/h2&gt; 非常有帮助。 ?. 在英语语义中是什么意思? @ChrisG

标签: javascript node.js reactjs axios


【解决方案1】:

更好的版本:

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;

快乐编码:)

【讨论】:

  • 谢谢!这就是我正在寻找的方法!别忘了setFetchCount(fetchCount + 1); :)
  • 很高兴听到。我很高兴 :) 请将此答案标记为已接受,因为这对您有帮助。
  • 或者只是setCurrentFetch({ ...currentFetch, ...response.data })
  • 是的,我明白了。更新了我的答案。无论如何,是的,您也可以这样做...response.data 方式,但不推荐,因为好的做法是只提取我们需要的东西。否则会在currentFetch 中添加不必要的道具。希望你理解哥们。
猜你喜欢
  • 2021-05-07
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 2010-11-11
  • 1970-01-01
  • 2014-08-04
  • 1970-01-01
相关资源
最近更新 更多