react如何更新state类型为数组的元素,并渲染到页面

有一个需求已知api:https://apitest.tianxiandao.c...
筛选data.datas.page中 home_type为"home1"的图片。并渲染到页面。我想将组件中的
state.ImgLists设为数组。如何在筛选图片完成的时候讲图片地址添加到state.ImgLists呢?
render()部分又怎么写呢? 还有我写的组件如何用ES6实现?

import React from 'react';

class Welcome extends React.Component {
    constructor(props) {
    super(props);
    this.state = {ImgLists: []};
    }
    componentDidMount() {
        let _this = this;
        let url = this.props.url;
        fetch(url)
        .then(function(response) {
        return response.json();
        }).then(function(data) {
        return data.datas.page
        }).then(function(page) {
            let filterArr = page;
            for(let i of filterArr) {
                for(let k of i) {
                    if(k.home_type === "home1") {
                        _this.setState({
                            ImgLists:k
                        })
                    }
                }
            }
        })
    
    }
  render() {
    return (
        <div>
            {
                this.state.ImgLists.map(function(item) {
                    return (
                        <li>1</li>
                    )
                })
            }
        </div>
    )
  }
}
export default Welcome;
阅读 8.4k
1 个回答

代码如下(请记得点赞采纳哦):

import React from 'react';

class Welcome extends React.Component {
    constructor(props) {
    super(props);
    this.state = {ImgLists: []};
    }
    componentDidMount() {
        const _this = this;
        let ImgLists=[];
        // let url = this.props.url;
        fetch("https://apitest.tianxiandao.cn/mapi/v1/home/index/page")
        .then((response)=>{
            return response.json();
        }).then(function(data) {
            data.datas.page.forEach((item1)=>{
                ImgLists=ImgLists.concat(item1.filter((item2)=>{
                    return item2.home_type==="home1";
                }));
            });
            _this.setState({
                ImgLists
            });
        }).catch(function(error) {
             console.log(error);
        });
    
    }
  render() {
    return (
        <div>
            {
                this.state.ImgLists.map(function(item,index) {
                    return (
                        <li key={index}><img src={item.image}/></li>
                    )
                })
            }
        </div>
    )
  }
}
export default Welcome;
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题