javascript - 对象无效问题

标签 javascript ruby-on-rails reactjs

我有以下组件,它很像 React.js 主教程。基本上,我有一个 api,我从中提取并尝试加载数据:

var Box = React.createClass({
   getInitialState: function () {
      return {
        data: {
          items: []
       }
      };
   },
   loadStuffFromServer: function() {
      $.ajax({
         url: this.props.url,
         dataType: 'json',
         cache: false,
         success: function(data) {
            this.setState({data: data});
         }.bind(this),
         error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
         }.bind(this)
     });
  },
  componentDidMount: function() {
    this.loadStuffFromServer();
  },
  render: function() {
    var blah = this.state.data;
    return (
       <div>
           { blah }
       </div>
    );
  }
});

但是,当我在那里放置 blah 时,我收到错误:Uncaught Error: Invariant Violation: Objects are not valid as a React child (found: object with keys {items}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of盒子.

我用 React Rails 和 <%= react_component('Box',url: "URLHERE", pollInterval: 1000) %> 调用我的组件

最佳答案

使用数组 (data.items)而不是对象

var blah = this.state.data.items;
__________________________^^^^^^___


render: function () {
   var blah = this.state.data.items.map(function (item) {
     return <p>
       { item.content }
     </p>;
   });

   return <div>
     { blah }
   </div>;
}

关于javascript - 对象无效问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34464280/

相关文章:

javascript - 使用 ComponentDidMount 中的 props 调用 Action

javascript - 如何使分页 "Next"按钮在数据表中看起来不被禁用

javascript - 按自定义属性搜索亚马逊 Cognito 用户

ruby-on-rails - PostgreSQL 复杂索引类型和排序

javascript - 根据所选项目填充选择下拉列表

javascript - Prev 和 Next 按钮在断点处无法正常工作

javascript - FullCalendar 单击编辑资源

javascript - 如果我知道多边形的 ID,如何更新多边形 Material ?

ruby-on-rails - 不同的前缀 : "/" and "http:/localhost:3000" with devise

javascript - 将react-router-dom链接传递到外部库