2017-08-08 16 views
2

私はaxiosポストを使用してモーダルを隠す/表示しようとしています。私は、エラーを取得未定義のプロパティ '非表示を読み取ることができません還元モーメントを使用してモーダルを表示しない

アイデア?

// dispatch to hide modal 
hide() { 
    this.props.dispatch(hideModal()); 
} 


// dispatch to show modal 
show() { 
    this.props.dispatch(
     showError({ 
      type: 'SHOW_MODAL', 
      modalType: 'SHOW_LOADING', 
      modalProps: { 
       onClose: hideModal, 
       text: 'Please complete all fields', 
      }, 
     }) 
    ); 
} 

submitForm(UserDetails) { 
    this.show(); 

    axios 
     .post('http://localhost:3001/api/users', UserDetails) 
     .then(function(response) { 
      this.hide(); 
     }) 
     .catch(function(error) { 
      console.log(error); 
     }); 
} 

答えて

1

axiosの関数内thisありません。あなたはこれを試みることができる :

submitForm(UserDetails) { 
    var self = this; 
    self.show(); 

    axios 
     .post('http://localhost:3001/api/users', UserDetails) 
     .then(function(response) { 
      self.hide(); 
     }) 
     .catch(function(error) { 
      console.log(error); 
     }); 
} 

これらはまた、このようなあなたのコンストラクタ内に結合することができます:あなたが今やっているよう

constructor(props) { 
    super(props); 

    this.hide = this.hide.bind(this); 
    this.show = this.show.bind(this); 
} 

は、あなたがそれらを使用することができます。後者は普通の関数で矢印(=>)関数で少なくとも動作しますが、thisがあなたのコードをどのように参照するのか分かりません。私は最初の答えに行くでしょう。

+0

あなたが提案した2番目の解決策はうまくいかないと思いますが、ここでは問題を引き起こす 'axios'' this'の問題です。 –

+0

私は同意しますが、私はそれが正しいと思います。 、しかし、通常の機能()でそれは動作しません... –

0

これはthis点の質問です。

hide =() => { 
    this.props.dispatch(...); // 1 
} 

show =() => { 
    this.props.dispatch(...); // 1 
} 

submitForm = (UserDetails) => { 
    this.show(); 

    axios 
     .post('http://localhost:3001/api/users', UserDetails) 
     .then((response) => { 
      this.hide(); // 2 
     }) 

} 

正しくためxxx =() => {}構文ES7へのマーク1位thisポイント。

とマーク2の場所this使用矢印機能が正しくポイントします。

関連する問題