Rendering List with Fetch in React

社会主义新天地 提交于 2019-12-21 23:46:10

问题


Trying to render a list of movies from a random API and eventually filter them.

componentDidMount() {
    var myRequest = new Request(website);
    let movies = [];

    fetch(myRequest)
        .then(function(response) { return response.json(); })
        .then(function(data) {
            data.forEach(movie =>{
                movies.push(movie.title);
            })
        });
     this.setState({movies: movies});
}

render() {
    console.log(this.state.movies);
    console.log(this.state.movies.length);
    return (
        <h1>Movie List</h1>
    )
}

If I render this I can only print my state and not access what is inside. How would I create a list of LIs and render a UL? Thanks


回答1:


A few things. fetch is asynchronous, so you're essentially just going to be setting movies to an empty array as this is written. If data is an array of movies, you can just set that directly in your state rather than copying it to a new array first. Finally, using an arrow function for the final callback in the promise will allow you to use this.setState without having to explicitly bind the function.

Finally, you can use JSX curly brace syntax to map over the movies in your state object, and render them as items in a list.

class MyComponent extends React.Component {
  constructor() {
    super()
    this.state = { movies: [] }
  }

  componentDidMount() {
    var myRequest = new Request(website);
    let movies = [];

    fetch(myRequest)
      .then(response => response.json())
      .then(data => {
        this.setState({ movies: data })
      })
  }

  render() {
    return (
      <div>
        <h1>Movie List</h1>
        <ul>
          {this.state.movies.map(movie => {
            return <li key={`movie-${movie.id}`}>{movie.name}</li>
          })}
        </ul>
      </div>
    )
  }
}



回答2:


First of all, since fetch is asynchronous, you will most likely call setState before the fetch call has completed, and you obviously don't want to do that.

Second, if the data returned is an array of movies, do not iterate over it, just assign the array altogether to the movies state variable.

So, in short, this is what your componentDidMount method should look like :

componentDidMount() {
  var myRequest = new Request(website);

  fetch(myRequest)
    .then(res => res.json())
    .then(movies =>
      this.setState({ movies }) // little bit of ES6 assignment magic 
    );
}

Then in your render function you can do something like:

render() {
  const { movies } = this.state.movies;
  return (
    <ul>
      { movies.length && movies.map(m => <li key={m.title}>{m.title}</li>) }
    </ul>
  );
}



回答3:


Gotten your movies in state you can do the next to render the list of movies:

render() {
  return (
    <h1>Movie List</h1>
    <ul>
      {
        this.state.movies.map((movie) =>
          <li key={movie}>movie</li>
        )
      }
    </ul>
  );
}


来源:https://stackoverflow.com/questions/47686011/rendering-list-with-fetch-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!