0

現時点では、次のように .erb ファイル内でコンポーネントをレンダリングします。

<%= react_component('Counter', number: @counter) %>

このコンポーネントには、次を使用する機能がありますpromised-xhr

push: function(operation) {

    if(operation) {
      new_number = this.state.number +1;
    } else {
      new_number = this.state.number -1;
    }

 // This call works.
 // this.setState({number: new_number})

     XHR.post("/update", {
      data: {
        count: new_number
      }
    }).then(function(response) {
   // XHR.post is successful, so I can log the response.
      console.log(response.body.number);
   // But setState does not work because of 'this'
      this.setState({number: reponse.body.number})
    })

}

this.setState({number: response.body.number)}thisはもはやコンポーネントではないため、機能しません。React.findDOMNode(this.refs.myComponent)コンポーネントを見つけて新しい状態をトリガーするために使用する予定です。

ただし、 を使用しreact_componentて ref を Counter コンポーネントに割り当てる方法がわかりません。

4

1 に答える 1

1

メモ化thisしてから、コールバック内でローカル変数を使用するのはどうですか?

push: function(operation) {
  // ... 
  // Store `this` as local variable `_this`:
  var _this = this 

  XHR.post("/update", {/*...*/})
    .then(function(response) {
    // use local variable `_this`, which still refers to the component:
      _this.setState({number: reponse.body.number
    })
}

補足として、ref役に立たないかもしれません。を呼び出すとgetDOMNode、React コンポーネントではなく、DOM ノード (ブラウザー組み込み) が作成されます。

于 2015-07-08T20:59:23.963 に答える