如何从Firebase获取数据并将其放入this.props - React

时间:2016-02-14 07:26:21

标签: javascript html reactjs firebase

所以,我有一个Firebase设置,我正在尝试将我的数据从snapshot.val()传入this.props.device,但是这个'this'在this.firebaseRef.on()函数中是'null' 。有什么想法吗?

var RegisteredDevice = React.createClass({
    mixins: [ReactFireMixin],

    componentWillMount: function() {
      this.firebaseRef = new Firebase("https://omniwolfdsn.firebaseio.com/Devices");

      this.firebaseRef.on('value', function(snapshot) {
        this.props.device = snapshot.val();
      });
    },

    propTypes: {

      name: React.PropTypes.string.isRequired,
      device: React.PropTypes.string,
      fire: React.PropTypes.string,
      noise: React.PropTypes.string,
      motion: React.PropTypes.string,
    }
)};

1 个答案:

答案 0 :(得分:0)

您可以将this作为第4个参数传递

  this.firebaseRef.on('value', function(snapshot) {

    this.props.device = snapshot.val();

  }, (error) => console.log( error ),  this);

根据文档,一次签名是

on(eventType, successCallback, [failureCallback], [context] )

所以第四个参数可以是this