在 fetch 调用中设置一个状态给我未定义?
Setting a state in fetch call gives me undefined?
您好,我正在尝试在我的获取调用中设置一个状态,当我尝试访问该状态时,它 returns 未定义。我不确定为什么会这样有人可以帮忙吗?
var [articlearray, setArticle]= React.useState([]);
var options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({headline: props.headline})
};
fet(options)
function fet(options){
fetch('/headlines', options).then(response => response.json()).then(data =>{
var newsData = data.newsArray
setArticle(newsData)
})
}
console.log(articlearray[0]);
您可以使用 useEffect
从 API 端点加载所有数据。 useEffect 上的空数组 []
意味着它将 运行 一次,在生命周期的开始。
var [articlearray, setArticle] = React.useState([]);
const fetchData = async () => {
var options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
headline: props.headline
})
};
fetch('/headlines', options).then(response => response.json()).then(data => {
var newsData = data.newsArray;
setArticle(newsData);
console.log(articlearray[0]);
})
}
useEffect(() => {
fetchData();
}, []);
您好,我正在尝试在我的获取调用中设置一个状态,当我尝试访问该状态时,它 returns 未定义。我不确定为什么会这样有人可以帮忙吗?
var [articlearray, setArticle]= React.useState([]);
var options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({headline: props.headline})
};
fet(options)
function fet(options){
fetch('/headlines', options).then(response => response.json()).then(data =>{
var newsData = data.newsArray
setArticle(newsData)
})
}
console.log(articlearray[0]);
您可以使用 useEffect
从 API 端点加载所有数据。 useEffect 上的空数组 []
意味着它将 运行 一次,在生命周期的开始。
var [articlearray, setArticle] = React.useState([]);
const fetchData = async () => {
var options = {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
headline: props.headline
})
};
fetch('/headlines', options).then(response => response.json()).then(data => {
var newsData = data.newsArray;
setArticle(newsData);
console.log(articlearray[0]);
})
}
useEffect(() => {
fetchData();
}, []);