【问题标题】:How to map a nested object in react in a rails associated models?如何在 Rails 关联模型中映射嵌套对象?
【发布时间】:2018-09-27 16:27:36
【问题描述】:

在设置一个包含许多 cmets 的简单帖子模型之后,使用 react 从帖子中获取 cmets 的最佳方法是什么?

例如在 Rails 中的循环是:

<ul>
<%= @post.comments.each do |c| %>
     <li><%= c.title %></li> 

<% end %>
</ul>

在反应中,地图是等价的,但在这种情况下,作为来自对象的地图仍然令人困惑。

var comments = this.state.comments.map(c => {

              return (
                 <div key={comment.id}>
                <ul >


                  <li>{comment.title}</li>


                </ul>

                  </div>

              );

            });

所以我已经尝试过了,但正如预期的那样没有奏效。那么,有人对 react 中的 map 嵌套数组有任何提示吗?

 var post = this.state.post.map(p => {

                  return (
                     <div key={comment.id}>
                    p.comments.map(c => {
                   <div key={ct.id}></div>
});

                      </div>

                  );

                });

【问题讨论】:

    标签: javascript ruby-on-rails reactjs


    【解决方案1】:

    以下两个选项中的任何一个都适合您。您必须对嵌套数组进行条件检查并添加返回。

    下面的 .map 与 return 一起使用

           const postItems = this.state.post && this.state.post.map(p => {
                  return (
                     <div key={comment.id}>
                        if(p.comments){
                             p.comments.map(c => {
                                 return <div key={ct.id}></div>
                             });
                         }
                      </div>
                  );
                });
    

    或 .map 无需返回即可工作

             const postItems = this.state.post &&  this.state.post.map(p => (
                     <div key={comment.id}>
                        if(p.comments){
                              p.comments.map(c => (
                                   <div key={ct.id}></div>
                              ));
                        }
                      </div>
                ));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      相关资源
      最近更新 更多