我的useEffect代码有什么问题,为什么我的状态变量为空? [英] What's wrong with my useEffect code, and why is my state variable empty?

查看:171
本文介绍了我的useEffect代码有什么问题,为什么我的状态变量为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,我不确定是什么引起了问题.

I have a problem and I'm not sure what's causing the problem.

所以我已经完成了使用外部api的提取,并且希望从api中打印出一些信息.我已经记录了数据和状态变量,以查看它们是否返回数据.我的问题是我没有从控制台的状态变量中获取任何数据.当我在控制台中登录时,它仅显示一个空数组.但是,当我登录console.log(data)时,会在控制台中获取数据.

So I have done a fetch with an external api and I want to print out some of the information from the api. I have logged the data and the state variable to see if they return the data. My problem is that I don't get any data from the state variable in the console. When I log it in the console it only shows an empty array. But I get the data in the console when I'm logging console.log(data).

当我在useEffect的末尾删除空数组时,它可以在控制台中运行,但是这是一个无休止的循环.如果将状态变量放入空数组,也会发生同样的事情.

When I remove the empty array at the end of useEffect, it works in the console but it's an endless loop. Same thing happens if I put the state variable in the empty array.

有人知道这个问题可能是什么吗?

Does anyone know what the problem could be?

export const Communication = () => {
  const [article, setArticle] = useState([])

  useEffect(() => {
    fetch('https://cors-anywhere.herokuapp.com/https://api.fortnox.se/3/articles', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Access-Token': accessToken,
        'Client-Secret': clientSecret
      }
    })
      .then((res) => res.json())
      .then((data) => {
        setArticle(data)

        console.log('json', data)
        console.log('article', article)
      })
  }, [])

推荐答案

思考JavaScript的工作方式.使用此语句,您可以声明两个变量:

Think about how JavaScript works. With this statement, you declare two variables:

const [article, setArticle] = useState([])

如果您想到article,则对外部函数的任何调用将无法将article分配给新值.这不仅是因为它是const;即使使用let,外部函数也无法更改它;我们没有指针之类的东西.这与这里发生的事情没有什么不同:

If you think about article, no call to an external function will be able to assign article to a new value. This is not just because it's const; even if let was used, an external function would not be able to change it; we don't have anything like pointers. It's no different than what's going on here:

function a() {
  let foo = 1;
  changeFoo(2);
}

function changeFoo(newValue) {
  // How do I change `foo` inside of function `a`? Spoiler, I cannot!
}

类似地,调用setArticle 无法更新商品价值.那不是React的工作方式.而是,下次您的组件调用useState时,它将收到新值.因此,这就是原因:

Similarly, calling setArticle has no way to update the article value. That's not how React works. Rather, the next time your component calls useState, it will receive the new value. Hence this is why:

setArticle(data);
console.log(article);

...将记录article的旧值.这并不意味着setArticle无效.这意味着您期望React太神奇了.下次调用article时,将在下一次渲染时为useState分配新值.如果您想记录文章的状态,请执行以下操作:

...is going to log the old value of article. This doesn't mean that setArticle didn't work; it means you're expecting React to be a little too magical. article will be assigned the new value on the next call to useState on the next render instead. If you want to log the changing article state, you'll want to do something more like:

export const Communication = () => {
  const [article, setArticle] = useState([])
  console.log('article', article);

  useEffect(() => {
    fetch('https://cors-anywhere.herokuapp.com/https://api.fortnox.se/3/articles', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'Access-Token': accessToken,
        'Client-Secret': clientSecret
      }
    })
      .then((res) => res.json())
      .then(setArticle)
  }, [])

  // ...
}

这篇关于我的useEffect代码有什么问题,为什么我的状态变量为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆