【问题标题】:ReactFire - get 'Objects are not valid as a React child' when binding Firebase to React stateReactFire - 将 Firebase 绑定到 React 状态时,获取“对象作为 React 子项无效”
【发布时间】:2016-02-17 00:12:01
【问题描述】:

我正在尝试将我在 Firebase 中的数据绑定到名为“notes”(一个数组)的反应状态,下面的代码遵循教程 here:

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'); 行不正常吗?

【问题讨论】:

  • 你确定错误在bindAsArray()吗?因为该代码对我来说看起来是正确的。此外,这个错误很常见,通常意味着你试图在render() 方法的虚拟 DOM 中包含一些错误

标签: javascript arrays object reactjs firebase


【解决方案1】:

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

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

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

类似的东西

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

【讨论】:

    【解决方案2】:

    this.ref 有点令人困惑,因为 React 的 this.refs - 另外,我不理解 this.ref.child。根据文档,这应该可行:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-02
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-02
    • 1970-01-01
    相关资源
    最近更新 更多