2017-08-08 57 views
2

我試圖使用axios發佈來隱藏/顯示模式。我得到的錯誤,無法讀取屬性'隱藏'undefined使用REDD隱藏顯示模式

任何想法?

// 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

this不是this Axios公司的功能之內。 你可以試試這個:

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

我不認爲你提出的第二種解決方案會工作,因爲這裏是'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 
     }) 

} 

標記1處this點從到ES7正確,因爲xxx =() => {}語法。

和標記2位this使用箭頭功能所以指向正確。