问题
I have a problem and I'm not sure what's causing the problem.
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).
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)
})
}, [])
回答1:
Think about how JavaScript works. With this statement, you declare two variables:
const [article, setArticle] = useState([])
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!
}
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);
...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)
}, [])
// ...
}
来源:https://stackoverflow.com/questions/62460016/whats-wrong-with-my-useeffect-code-and-why-is-my-state-variable-empty