reactjs - 变量显示为undefined

时间:2016-03-03 20:54:13

标签: javascript reactjs

我对reactjs感兴趣,并尝试从firebase中检索的值填充表单。

这是取值的地方。

componentWillMount: function () {

    var projectId = this.props.params.key;
    this.fb = new Firebase(rootUrl + 'items/');
    var projectRef = this.fb.child(projectId);

    var subjectproject = "NA";


    projectRef.child("subject").on("value", function(snapshot) {
        subjectproject = snapshot.val();
    });


},

这是我要填充的表单输入

<div className="col-lg-6">
           <div class="input-group">
               <label class="control-label required" for="project_project_title">Subject</label>
                     <input defaultValue={subjectproject} value={this.state.subject} placeholder="Subject" onChange={this.handleInputChangeSubject} type="text" className="form-control"/>
            </div>
  </div>

我得到的只是projectSubject未定义。如何创建可用于提供默认值的变量。

编辑 -

 projectRef.child("subject").on("value", function(snapshot) {
        textsubject = (snapshot.val());
        this.setState({subject: textsubject});
    });

引发FIREBASE WARNING: Exception was thrown by user callback. TypeError: this.setState is not a function

1 个答案:

答案 0 :(得分:1)

subjectproject - 在componentWillMount中声明为局部变量。它在渲染方法中不可见。

请参阅:https://facebook.github.io/react/docs/forms.html#default-value

The defaultValue and defaultChecked props are only used during initial render.

示例(来自评论):

componentWillMount: function () {
    var self = this;

   // some code

    projectRef.child("subject").on("value", function(snapshot) {
        self.setState({
            subjectproject: snapshot.val()
        });
    });


},