且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在React中使用抓取渲染列表

更新时间:2023-11-10 20:22:58

一些事情. fetch是异步的,因此您基本上只需要在编写影片时将影片设置为空数组即可.如果data是电影数组,则可以直接将其设置为您的状态,而不是先将其复制到新的数组中.最后,在promise中为最终回调使用箭头函数将使您可以使用this.setState,而不必显式绑定该函数.

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.

最后,您可以使用JSX大括号语法来映射状态对象中的影片,并将其呈现为列表中的项目.

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