【问题标题】:Looping through a list of Objects is not displaying properly循环遍历对象列表未正确显示
【发布时间】:2019-09-10 03:29:20
【问题描述】:

我正在尝试显示一个对象循环。它通过console.log 显示,但它没有显示在浏览器上。我目前的代码如下:

class Profile extends React.Component {
    renderList() {
        const { booking } = this.props;  
        booking && Object.keys(booking).map(x => {
            console.log("booking", booking[x].item_name);
            return <div>{booking[x].item_name}</div>
        })
    }
    render() {
        return (
        {this.renderList()}
        )
    }
}

我尝试了for 循环、map 以及 lodash,我得到了相同的结果,所以我认为这不是对象循环方法的问题。

【问题讨论】:

    标签: javascript reactjs loops object


    【解决方案1】:

    您还需要返回元素。试试这个:

    class Profile extends React.Component {
        renderList() {
            const { booking } = this.props;  
            if (booking) {
                return Object.keys(booking).map(x => {
                    return <div>{booking[x].item_name}</div>
                })
            }
            return null;
        }
        render() {
            return this.renderList();
        }
    }
    

    可能return bookings &amp;&amp; Object.keys(booki... 也可以。

    更新:return ({ this.renderList() })会报jsx语法错误,应该写成如上。

    【讨论】:

    • 只是想知道为什么会出错?是因为它是单行吗?我的包裹在额外的 JSX 元素中,没有给我错误
    • @Kevvv 可能是因为没有必要将 js 表达式模板作为根。就像只返回表达式本身一样,因为元素内部需要模板才能让反应知道“嘿,这是这些大括号内的 JS”。因此,它与单行无关。
    【解决方案2】:
    1. 您显然从 renderList 方法中省略了 return 关键字
    2. 您应该在从渲染函数返回时将 renderList 方法调用包装在根单个元素中。 附带说明一下,为了获得更好的编码体验,不要忘记在基于类的组件中定义 defaultProps 静态属性,并在功能组件中定义默认的 ES2015 参数
    class Profile extends React.Component {
         static defaultProps = {
            booking: {
              first_item: {
                item_name: "First name"
              },
              second_item: {
                item_name: "Second name"
              }
            }
         }
    
        renderList = () => {
            const { booking } = this.props;  
            return booking ? Object.keys(booking).map(x => <div>{booking[x].item_name}</div>) : null 
        }
    
        render() {
            return (
              <div>
               {this.renderList()} 
              </div>  
            )
        }
    }
    

    【讨论】:

    • "从渲染函数返回时,您应该将 renderList 方法调用包装在根单个元素中。" 如果您的意思是返回数组不起作用,那么:不,数组可以正常工作demo
    猜你喜欢
    • 1970-01-01
    • 2010-10-22
    • 2013-05-29
    • 2015-06-27
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 2022-06-29
    • 1970-01-01
    相关资源
    最近更新 更多