Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

javascript - fetching random json getting first undefined then result

Beginner on reactjs here, trying to fetch random json, getting the result i want to get, but not the way i want it, for some reason it prints first 'undefined' then after that the result. Why cant i get just the result and without this '?' my code:

import { useEffect, useState } from "react";
import "./App.css";

function App() {
  const [thumbnail, setThumbnail] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/photos")
      .then((response) => response.json())
      .then((json) => {
        setThumbnail(json);
      });
  }, []);

  console.log(thumbnail[0]?.thumbnailUrl);
  return (
    <div className="App">
      <h1>Build</h1>
      <p></p>
    </div>
  );
}

export default App;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

console.log() inside App() directly will use the initial state of. thumbnail which is the empty, so it will show undefined.

To check the thumbnail, you should use another useEffect with adding a thumbnail dependency.

useEffect(() => {
  if (thumbnail.length > 0) {
    console.log(thumbnail[0].thumbnailUrl);
  }
}, [thumbnail]);

import { useEffect, useState } from "react";
import "./App.css";

function App() {
  const [thumbnail, setThumbnail] = useState([]);
  const [isLoaded, setLoaded] = useState(false);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/photos")
      .then((response) => response.json())
      .then((json) => {
        setLoaded(true);
        setThumbnail(json);
      });
  }, []);

  useEffect(() => {
    if (isLoaded) {
      console.log(thumbnail[0]?.thumbnailUrl);
    }
  }, [thumbnail]);

  return (
    <div className="App">
      <h1>Build</h1>
      <p></p>
    </div>
  );
}

export default App;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...