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

How do I get data from Firebase and put it in this.props - React

本文关键字:this props React Firebase 获取 数据      更新时间:2023-09-26

所以,我有一个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,
    }
)};

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

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

根据文档,一次的签名是

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

所以第四个参数可以this