[英]Getting Error while mapping data from Geo ipify API in ReactJS
Geoipify data Screenshot Geoipify 数据截图
I am getting error that "Cannot read property 'country' of undefined" when I load page after I refresh page.刷新页面后加载页面时出现“无法读取未定义的属性‘国家’”的错误。 When I first entered {IPdata.location.country} it rendered.
当我第一次输入 {IPdata.location.country} 它呈现。 But after I refreshed again there was error.
但是我再次刷新后出现错误。 Need help here please!
请在这里需要帮助!
Update : I am getting this error only for IPdata.location.country and IPdata.location.timezone.更新:我只收到 IPdata.location.country 和 IPdata.location.timezone 的这个错误。 Page is rendering fine with IPdata.ip and IPdata.isp
页面使用 IPdata.ip 和 IPdata.isp 渲染良好
const [IPdata, SetIPData] = useState([]);
useEffect( () => {
getIp()
},[]);
async function getIp() {
const response = await fetch(`https://geo.ipify.org/api/v1?apiKey=${APP_KEY}&ipAddress=8.8.8.8`);
const data = await response.json();
console.log(data);
SetIPData(data)
}
return (
<div>
<div className="container">
<div className="input-section">
<h1 className="header"> IP Address Tracker</h1>
<form className="search-form">
<input className="search-input" type="text" placeholder="Search for any IP address or domain" />
<button className="search-button" type="submit"> Go! </button>
</form>
</div>
<div className="result-container">
<Result
heading={"IP Address"}
searchResult={IPdata.ip}
/>
<Result
heading={"Location"}
searchResult={IPdata.location.country}
/>
<Result
heading={"Timezone"}
searchResult={"UTC" + IPdata.location.timezone}
/>
<Result
heading={"ISP"}
searchResult={IPdata.isp}
/>
</div>
</div>
</div>
try adding -尝试添加 -
const [loaded, setLoaded] = useState(false);
useEffect(()=>{
setLoaded(true);
},[IPdata])
and for your render just check if loaded is true or not -对于您的渲染,只需检查加载是否为真 -
return (
loaded ? (
<div>
<div className="container">
<div className="input-section">
<h1 className="header"> IP Address Tracker</h1>
<form className="search-form">
<input className="search-input" type="text" placeholder="Search for any IP address or domain" />
<button className="search-button" type="submit"> Go! </button>
</form>
</div>
<div className="result-container">
<Result
heading={"IP Address"}
searchResult={IPdata.ip}
/>
<Result
heading={"Location"}
searchResult={IPdata.location.country}
/>
<Result
heading={"Timezone"}
searchResult={"UTC" + IPdata.location.timezone}
/>
<Result
heading={"ISP"}
searchResult={IPdata.isp}
/>
</div>
</div>
</div>) : <p>Loading...</p>
Looks like data is being rendered before loading.看起来数据在加载之前正在呈现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.