简体   繁体   中英

How can I display the results of map function in jsx?

I'm slowly learning react and trying to display the results of my searchMap function (movie title/poster) with the TMDB API. I can log the information I need to the console, but I get undefined variables and other errors when trying to display the information in the commented div. https://codesandbox.io/s/ddmdu4

function App() {
  const search = async (event) => {
    const searchQuery = event.target.value;
    if (searchQuery) {
      const searchReq = await fetch(
        `https://api.themoviedb.org/3/search/movie?api_key=${process.env.API_KEY}&query=${searchQuery}`
      ).then((res) => res.json());
      const searchResults = searchReq.results;
      searchMap(searchResults);
    }
  };

  const searchMap = (searchResults) => {
    searchResults.map((movie) => {
      console.log(`${movie.title}`);
      console.log(`${movie.backdrop_path}`);
    });
  };

  return (
    <div className="App">
      <div>
        <input type="text" onChange={search} placeholder="Search"></input>
      </div>

      <div>{/* Display movie title/poster*/}</div>
    </div>
  );
}

export default App;

Since you want to update the DOM each time the result changes I would recommend using that inside of a state like so:

  const [searchResults, setSearchResults] = React.useState([]);

In your async search function update the state by using its appropiate "setter":

      .then((res) => res.json());
      setSearchResults(searchReq.results);

And inside your return you can map the result as follows:

      <div>
        {searchResults.map((movie) => (
          <>
            <div>{movie.title}</div>
            <div>{movie.backdrop_path}</div>
          </>
        ))}
      </div>

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