2017-04-13 12 views
3

私はこの単純な例でパスワードワードフィールドを乱数で更新しようとすると、パスワードフィールドを持つredux-formを持っています。結果に 'this'をバインドするにはどうすればいいですか?'これ'をaxiosに渡して 'then'を約束しますか?

axios.get('https://www.random.org/integers/?num=1&min=1&max=20&col=1&base=10&format=plain&rnd=new').then(function(result) { 
     this.props.change('password', result.data); 
    }).catch(function(error) { 
      this.props.change('password', '999'); 
     }); 

私はES5 var this1 = thisを使用すると上記のロジックが正常に動作することを知っています。これはうまく動作するthis1を使用してください。

よろしくお願いいたします。

答えて

2

あなたが今述べてきた方法、すなわち

var $this = this 
var func = function() { 
    $this.props.doSomething() 
} 

それとも、あなたは右thisコンテキストで実行される機能をbindすることができますを使用することができます。バニラJSでは、bindを使用することによってそれを行うことができます:匿名関数へthisを結合ES6で

var func = function() { 
    this.props.doSomething() 
} 
// now this inside func will always be whatever it was here 
func = func.bind(this) 

arrow functionsで簡素化されました:このことができます

const func =() => { 
    // this will be always whatever it was where this func was defined 
    this.props.doSomething() 
} 

希望を!

+0

私は変更を加え、ES6太鼓の機能を使用しましたが、「this」にアクセスできません。私もそれを通過しようとしました。 [注:今すぐpromise.allを使用] const func =()=> {Promise.all([axios.get( 'https://www.random.org/integers/?num=1&min=1&max=20&col=1&base = 0&format = plain&rnd = new ')]).then(function(result){ ) ] .DATA); }) .catch(関数(誤差){ はconsole.log( '約束誤差='、エラー); this.props.change( 'パスワード'、 '999'); }) ; }; func(this); – Pat

+0

何らかの理由で、あなたがaxiosを呼び出す関数が正しい 'this'コンテキストを持たないのです。太い矢印の関数を使うことは 'var $ this = this'を実行する素晴らしい方法です。 – jakee

+0

ありがとうございました。 – Pat

関連する問題