ReactFire-获取'对象作为React子对象无效'将Firebase绑定到React状态时

ReactFire - get 'Objects are not valid as a React child' when binding Firebase to React state

本文关键字:对象 React Firebase 绑定 状态 无效 获取 ReactFire-      更新时间:2023-09-26

我正试图用下面的教程代码将Firebase中的数据绑定到名为"notes"(数组)的反应状态:

var Profile = React.createClass({
  mixins: [Router.State, ReactFireMixin],
  getInitialState: function() {
    return {
      bio: [],
      repos: [],
      notes: []
    }
  },
  componentDidMount: function() {
    this.ref = new Firebase('https://myname-github-notetaker.firebaseio.com');
    var childRef = this.ref.child(this.getParams().username);
    this.bindAsArray(childRef, 'notes');
  },
...
});

我在控制台上得到了这个错误:

Uncaught Error:
Invariant Violation: Objects are not valid as a React child (found: object with keys {.value, .key}).
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.

这是什么意思?线路this.bindAsArray(childRef, 'notes');是否工作不正常?

firebase返回一个对象数组。当你做这个

{this.props.notes.map(function(note,index){
 return <li key={index}>{note}</li>
})}

{注意}这是一个对象,我认为您需要通过对象键再次循环或使用https://www.npmjs.com/package/react-addons-create-fragment在您的应用程序中。

像这样的

var addons = require('react-addons-create-fragment');
return <li key={index}>{addons(note)}</li>

由于React的this.refsthis.ref有点令人困惑——而且,我不理解this.ref.child。根据文档,这应该有效:

var ref = new Firebase('https://myname-github-notetaker.firebaseio.com'); //may need .com/something here
this.bindAsArray(ref, 'notes');