【问题标题】:Object appears to be empty inside of react render() even if previous logging proves that it's not对象在 react render() 内部似乎是空的,即使之前的日志证明它不是
【发布时间】:2016-06-29 16:26:06
【问题描述】:

我的 React 应用中有这个组件:

class ChannelList extends React.Component {
    render() {
        console.log("1. return: " + JSON.stringify(this.props.channels));
        return (
            <ul>
                {this.props.channels.map(chan => {
                    console.log(JSON.stringify(chan));
                    return (
                        <Channel
                            key={chan.id}
                            channel={chan}
                            {...this.props} // Pass all properties
                        />
                    )
                })}
            </ul>
        )
    }
}

第一个日志方法是这样写的:1. return: [{"channel":{"id":1,"name":"asdf"}}] 第二种日志方式是这样的:{"channel":{"id":1,"name":"asdf"}}

但是在运行此代码时,我收到一条错误消息,即每个孩子都应该有一个唯一的“密钥”。 问题似乎是当我使用chan.id 时,对象是空的。 因为我在证明它不是之前只记录了三行,所以一定有其他问题。我是 JavaScript 新手,尤其是 React。

我的语法或尝试访问 id 值的方式有问题吗?

【问题讨论】:

  • 是的,您实际上并没有注意您记录的对象 :)

标签: javascript arrays json reactjs


【解决方案1】:

使用 chan.channel.id

class ChannelList extends React.Component {
    render() {
        console.log("1. return: " + JSON.stringify(this.props.channels));
        return (
            <ul>
                {this.props.channels.map(chan => {
                    console.log(JSON.stringify(chan));
                    return (
                        <Channel
                            key={chan.channel.id}
                            channel={chan}
                            {...this.props} // Pass all properties
                        />
                    )
                })}
            </ul>
        )
    }
}

【讨论】:

  • 在这个问题上敲了一个小时,却没有看到明显的结果。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-16
  • 1970-01-01
  • 2014-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多