javascript - react : requesting and iterating through images in JSON

标签 javascript reactjs

我对 React 完全陌生,刚刚开始通过 Facebook 上的 React 教程进行学习。我正在尝试从 JSON 文件中获取图像并以帖子的形式重复它们(如 Angular 的 ng-repeat),就像 Instagram 一样。我最初有一个工作注释部分,但现在它坏了,因为我开始添加更多我认为可以修复它的代码。事情变得如此草率,我不知道该怎么办了。

因此,根据我读到的内容,我应该通过“componentDidMount”发出 GET 请求。我看到使用 $getJSON、$.ajax、$.get 的源,但我对使用哪些以及如何处理它感到困惑。

let PostImage = React.createClass({
  getInitialState: function() {
    return {
      postImage: []
    };
  },

  componentDidMount: function() {
    var self = this;
    $.get(this.props.source, function(result) {
      var collection = result.data.children;
      this.setState({
        postImage: collection
      });
    }.bind(this));
  },

  render: function() {
    images = this.state.postImage || [];
    return (
      <div>
        Images: {images.map(function(image){
          return <img src={image}/>
        })}
      </div>
    );
  }
});
React.render(
  <PostImage source="https://codesmith-precourse.firebaseio.com/instagram/-JqL35o8u6t3dTQaFXSV.json" />,
  document.getElementById('content')
);

我的React.render当前位于PostImage上,但最高级别的组件是InstagramPost(请参见下面的Plnker)。我尝试将其切换到 InstagramPost 但它坏了,所以我也很困惑。在我的控制台中,我也看到了

$ is not defined

我附上了一个Plnker供引用:http://plnkr.co/edit/AYxUjameK6dAqCYUiwQT?p=info

如果您也可以帮助我的评论部分正常工作,那就太好了。提前致谢。

编辑:忘记在 Plnker 中包含 jQuery。

最佳答案

首先,您使用的是 jQuery $.get 因此您必须包含 jQuery 脚本

 <script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0="   crossorigin="anonymous"></script>

jQuery $.get 已经作为数据返回,因此您不需要再次执行 result.data,如果您不熟悉 jQuery $.get 读取 here

最终的 componentDidMount 应该如下所示

componentDidMount: function() {
  var self = this;
  $.get(this.props.source, function(result) {
    var collection = result;
    this.setState({
      postImage: collection
    });
  }.bind(this));
},

对于CommentBox,只需传递data={data}即可

关于javascript - react : requesting and iterating through images in JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37871984/

相关文章:

javascript - 具有小图形的 Neo4J 在 Ubuntu 16.04 上使用大量内存

javascript - React JS 如何更改除单击按钮 onClick 之外的元素中的字体颜色?

javascript - 非同步启动 Javascript 间隔并在运行 3 次后停止

javascript - Redux 表单 : Input stays with 'touched: false'

css - React Native Android 文本有额外的底部填充

Javascript&Css - onclick() 上的图像修改

javascript - Yammer CORS 错误仅针对某些 API 调用出现

javascript - 在 React 项目中添加 Redux

reactjs - 奇怪的 React 编译器行为

javascript - 将普通函数连接到 Redux 的 mapDispatchToProps