gpt4 book ai didi

javascript - Javascript 中带父级和不带父级的 json 上的 .map 方法

转载 作者:行者123 更新时间:2023-12-03 09:43:03 24 4
gpt4 key购买 nike

我正在做React + Rails应用程序,对于JSON我使用默认的jbuilder。但正如 React-rails 官方文档建议的那样,我向 JSON 添加一个根节点,如下所示:

{
"comments":
[
{"id":1,"author_name":null,"comment_text":null,"url":"http://localhost:3000/comments/1.json"}
]
}

在我的 Javascript 文件中我想做这样的事情:

var commentNodes = this.props.comments.map(function(comment,index){
return (
<Comment author_name={comment.author_name} comment_text={comment.comment_text} key={index} />
);
});

但是现在我有了根节点,我无法使用 this.props.comment.map 我收到错误:

Uncaught TypeError: this.props.comments.map is not a function

编辑:我向组件添加注释如下:

<CommentList comments={this.state.comments}/>

最佳答案

试试这个:

const jsonObj = {
"comments": [
{ "id":1, "author_name":null, "comment_text":null, "url":"http://localhost:3000/comments/1.json"}
]
}

this.setState({
comments: jsonObj.comments
})

<CommentList comments={this.state.comments} />

// in render() of CommentList
return (
<div>
{this.props.comments.map(this._createComment)}
</div>
);

_createComment({author_name, comment_text, id}) {
return (
<Comment
author_name={author_name}
comment_text={comment_text}
key={id} />
);
}

这是一个simple DEMO如何使用 .map

关于javascript - Javascript 中带父级和不带父级的 json 上的 .map 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31129926/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com