[英]'imgSrc' is not defined no-undef
考虑一下:
useEffect(() => {
let imageUrlRequest = axios.get(imageEndPointString).then(function (response) {
console.log('call made')
let imgSrc = response.data[0].data.children[0].data.url;
console.log(imgSrc)
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
},[]);
return (
<div className="game__image">
<h2>IMAGE URL: {imgSrc}</h2>
<img src={imgSrc} />
</div>
);
为什么imgSrc
是未定义的?
我也试过这个
let imgSrc;
useEffect(() => {
let imageUrlRequest = axios.get(imageEndPointString).then(function (response) {
console.log('call made')
imgSrc = response.data[0].data.children[0].data.url;
console.log(imgSrc)
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
},[]);
return (
<div className="game">
<img src={imgSrc} />
</div>
);
但图像仍然无法通过。 为什么?
在块内声明的 Javascript 变量只能在此块(本地范围)中使用。 此外,在 React 中,如果您想根据某个值更改视图,则必须使用
setState<\/code>函数让 React 知道何时应该重新渲染视图。
因此,在您的示例中,您需要执行以下操作:
const [imgSrc, setImgSrc] = useState(null);
useEffect(() => {
let imageUrlRequest = axios.get(imageEndPointString).then(function (response) {
console.log('call made')
setImgSrc(response.data[0].data.children[0].data.url);
console.log(imgSrc)
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
}); },[]);
return (
<div className="game__image">
<h2>IMAGE URL: {imgSrc}</h2>
<img src={imgSrc} />
</div> );
我认为这是因为在第一次渲染时(在 useEffect 之前),您尝试使用变量
imgSrc<\/code>作为图像源,因此在执行
useEffect<\/code>之前会出现错误。
您可以做的是在返回时使用默认值,以防
imgSrc<\/code>在那一刻仍未定义。
就像是
<img src={imgSrc || "anotherurl.com"} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.