React 获取并显示 Rails 中的附件

React get and show attached files in Rails

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

情况如下:

在 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>
      );
    });

事情永远是 rails 载波 attachment/files。在数组中创建一个对象,很多人仍然对如何抓取和渲染这些文件有疑问。

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

旁白:考虑一下您的代码片段:

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是一个数组,所以它在您调用的路径中没有任何数据。 "path into the object" 我只是指按点符号顺序调用的一系列键。