【问题标题】:How to assign data to a variable from axios get() response如何从 axios get() 响应中将数据分配给变量
【发布时间】:2021-06-14 17:24:14
【问题描述】:

我正在尝试使用 Express (axios) 构建一个 React 应用程序。

我能够使用 get() 方法从 MongoDB 获取对象数组。目前该列表已打印到控制台。如何将它分配给一个变量,以便我可以使用该数组进行进一步的操作?

useEffect(() => {
    const expensesListResp = async () => {
      await axios.get('http://localhost:4000/app/expenseslist')
      .then(
        response => console.log(response.data))
    }
    expensesListResp();
  }, []);

非常感谢!

【问题讨论】:

标签: reactjs http async-await axios get


【解决方案1】:

您可以通过以下方式分配它,假设您有一个数组posts

const [posts, setPosts] = useState([]);

useEffect(() => {
  axios.get('url')
  .then(res => setPosts(res.data))
  .catch(err => console.log(err));
}, [])

在你的代码中,你可以这样做:

const [resultArray, setResultArray] = useState([]);

useEffect(() => {
    const expensesListResp = async () => {
      await axios.get('http://localhost:4000/app/expenseslist')
      .then(
        response => setResultArray(response.data))
    }
    expensesListResp();
  }, []);

【讨论】:

  • 它有效并且是一个很好的解决方案!非常感谢
  • 从哪里导入 useState?有反应吗?
  • @PurnajyotiBhaumik 是的,它是从 React Hooks 导入的。
【解决方案2】:

我假设您在console.log(response.data) 上打印了数据,并且您希望将其分配给一个变量以便您可以正确使用它?

如果您已经在使用 async 函数,只需在 await 之前使用您想要的任何变量名称来命名它。

for example:

const expensesListResp = async () => {
      const "your variable name" = await axios.get('http://localhost:4000/app/expenseslist')
    }

如果您想在整个应用程序中使用该变量数据,您还可以将该变量保存在您的状态中。

【讨论】:

    猜你喜欢
    • 2020-10-23
    • 2020-07-02
    • 1970-01-01
    • 2019-07-18
    • 2020-05-19
    • 1970-01-01
    • 2020-11-02
    • 2023-03-08
    • 1970-01-01
    相关资源
    最近更新 更多