简体   繁体   中英

'imgSrc' is not defined no-undef

Consider this:

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>
  );

Howcome imgSrc is undefined?

I also tried this

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>
  );

but the image still won't come through. why?

In Javascript variables that are declared inside a block can be used only in this block (local scope). Furthermore, in React if you want to change your view based on some value you must use the setState<\/code> function to allow React to know when it should re-render the view.

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>   );

I think its because on the first render (before the useEffect) you are trying to use the variable imgSrc<\/code> as the image source, so you get an error before the useEffect<\/code> executes. What you can do is using a default value on your return in case imgSrc<\/code> is still undefined at that moment. Something like

<img src={imgSrc || "anotherurl.com"} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM