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

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

问题描述

尝试从随机 API 呈现电影列表并最终过滤它们.

componentDidMount() {var myRequest = 新请求(网站);让电影 = [];获取(我的请求).then(function(response) { return response.json(); }).then(函数(数据){data.forEach(电影 =>{电影.push(电影.title);})});this.setState({movies: movies});}使成为() {控制台.log(this.state.movi​​es);console.log(this.state.movi​​es.length);返回 (<h1>电影列表</h1>)}

如果我渲染它,我只能打印我的状态而不能访问里面的内容.我将如何创建 LI 列表并呈现 UL?谢谢

解决方案

一些事情.fetch 是异步的,因此您实际上只是在编写时将电影设置为一个空数组.如果 data 是一个电影数组,你可以直接在你的状态中设置它,而不是先将它复制到一个新数组中.最后,在 Promise 中使用箭头函数作为最终回调将允许您使用 this.setState 而无需显式绑定函数.

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

class MyComponent 扩展 React.Component {构造函数(){极好的()this.state = {电影:[]}}组件DidMount() {var myRequest = 新请求(网站);让电影 = [];获取(我的请求).then(response => response.json()).then(数据 => {this.setState({电影:数据})})}使成为() {返回 (

<h1>电影列表</h1><ul>{this.state.movi​​es.map(movie => {return <li key={`movie-${movie.id}`}>{movie.name}</li>})}</ul></div>)}}

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

解决方案

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

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

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