在React中使用抓取渲染列表 [英] Rendering List with Fetch in React

查看:58
本文介绍了在React中使用抓取渲染列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试通过随机API渲染电影列表,并最终对其进行过滤.

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

如果渲染此图像,则只能打印我的状态,而不能访问其中的内容. 如何创建LI列表并呈现UL? 谢谢

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

推荐答案

一些事情. 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>
    )
  }
}

这篇关于在React中使用抓取渲染列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆