[英]why does this console.logconsole.log(data.lyrics) gives me undefined in react.js?
Would you please tell me what I'm doing wrong here?你能告诉我我在这里做错了什么吗?
import { useState,useEffect } from 'react';
const useFetchData = (url) => {
const [data,setData]=useState( [] );
useEffect(()=>{
fetch(url,{
crossDomain:true,
headers:{
'Content-Type': 'application/json',}
})
.then(res =>{
return res.json();
})
.then(dataa =>{
/* setData(dataa.message.body.track_list.map(trc =>{
return [[trc.track.track_name],[trc.track.artist_name],[trc.track.album_name]];
}));*/
setData(dataa.message.body);
/* data.message.body.track_list.trac.track.map((trac)=>{
})
console.log(data);
console.log(dataa.message.body);*/
}).catch(err => console.log(err));
console.log(data.lyrics);
},[])
return data;
}
export default useFetchData;
Because you're calling data
from inside the useEffect
hook, you're only getting the value of data
at the point where the hook was executed.因为您是从
useEffect
挂钩内部调用data
,所以您只能在执行挂钩时获取data
的值。 setData
doesn't update the data
variable immediately, but updates the state and triggers a rerender of the component. setData
不会立即更新data
变量,而是更新 state 并触发组件的重新渲染。
If you move the console.log(data.lyrics);
如果你移动了
console.log(data.lyrics);
out of the hook, you'll see that once the component is rerendered its value should be correct.摆脱困境,你会看到一旦组件被重新渲染,它的值应该是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.