【问题标题】:React get and show attached files in Rails在 Rails 中反应获取并显示附件
【发布时间】:2018-12-12 21:08:06
【问题描述】:

似乎是一个简单的问题,但我不知道为什么这会造成一点压力。

情况如下:

在 Rails 中获取 Post.show 上的附件后

  async getAttachments() {
    // this.setState({showProgress: true})
    let auth_token = window.localStorage.getItem("auth_token");
    let post_id = this.props.match.params.id;
    fetch(`/posts/${post_id}/attachments`, {
      method: "GET",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        Access: auth_token
      }
    })
      .then(response => response.json())
      .then(json => {
        this.setState({
          attachments: json.attachments,

          image: json.attachments.image,
          thumb: json.attachments.image.thumb,
          url: json.attachments.thumb.url
        });
      })
      .catch(error => {
        console.error(error);
      });
  }

我决定照常渲染

{this.state.attachments}

但没有渲染。

所以我尝试映射然后我尝试了

   var attachments = this.state.attachments.map(a => {
      return (
        <div key={a.id}>
          <img source={a.thumb} />

          <img source={a.url}>{a.url}</img>
        </div>
      );
    });

问题是轨道载波附件/文件。在数组中创建一个对象,很多人仍然怀疑如何抓取和渲染这些文件。

【问题讨论】:

    标签: javascript ruby-on-rails reactjs carrierwave


    【解决方案1】:

    HTML image 标记使用名为 src 的属性,而不是 source。那是你的问题。

    旁白:考虑一下您的代码的这个 sn-p:

    this.setState({
      attachments: json.attachments,        // OK, keep  
    
      image: json.attachments.image,        // bad path into the object  
      thumb: json.attachments.image.thumb,  // bad path into the object  
      url: json.attachments.thumb.url       // bad path into the object
    });
    

    应删除以imagethumbattachment 开头的三行。

    使用代码而不删除这些行的结果将是您的状态如下所示:

    {
      attachments:  <an array of attachments>,  // correct, wanted, should keep  
      image: undefined,
      thumb: undefined,  
      url: undefined
    }
    

    这是因为json.attachments 是一个数组,所以它在您调用的路径中没有任何数据。通过“进入对象的路径”,我只是指按点符号顺序调用的键序列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 2021-01-31
      • 1970-01-01
      • 2022-01-09
      相关资源
      最近更新 更多