2016-02-13 74 views
0

我遇到了這個測試問題,我不知道如何測試組件settimeout。任何人都有關於如何測試以下組件的建議:settimeout?非常感謝反應如何用setTimeout測試出反應組分

import React, { PropTypes, Component } from 'react'; 
import styles from '../../../css/notification.css'; 

export default class Notification extends Component { 
    static propTypes = { 
     tagMetaUpdate: PropTypes.shape({ 
      submitUpdatedTagDataSuccessful: PropTypes.bool 
     }), 
     actions: PropTypes.shape({ 
      resetUpdatedTagDataSuccessfulFlag: PropTypes.func 
     }) 
    }; 

    constructor(props) { 
     super(props); 
     this.state = { 
      showMessage: true 
     }; 
    } 

    hideMessage(actions) { 
     this.timer = setTimeout(() => { 
      this.state.showMessage = false; 
      actions.resetUpdatedTagDataSuccessfulFlag(); 
      this.forceUpdate(); 
     }, 3000); 
    } 

    render() { 
     const { tagMetaUpdate, actions } = this.props; 
     const output = (tagMetaUpdate.submitUpdatedTagDataSuccessful && this.state.showMessage) ? 
      <div className={styles.notification}>Tag meta data successfully edited.</div> : null; 

     if (this.props.tagMetaUpdate.submitUpdatedTagDataSuccessful) { 
      this.hideMessage(actions); // HERE IS THE BIT BLOCKING ME 
     }else { 
      this.state.showMessage = true; 
     } 

     return <div>{output}</div>; 
    } 
} 

回答

1

直接改變狀態通常是不明智的。嘗試使用this.setState({}),並且當您調用setState時,this.forceUpdate是不必要的。 React會自己更新你的組件。

另外,嘗試使用render方法僅執行呈現。沒有變異狀態和所有這一切。

如果你直接在渲染方法中做this.setState({ showMessage: true }),反應會抱怨它 - 這是不允許的。

React提供稱爲componentWillRecievePropscomponentWillUpdate的生命週期掛鉤方法。你可以使用它們來檢查道具是否改變,然後相應地進行setState。

componentWillReceiveProps(nextProps){ 
    if(!_.isEqual(nextProps, this.props) { 
    if(nextProps.tagMetaUpdate.submitUpdatedTagDataSuccessful){ 
     this.setState({ showMessage: true }) 
     this.timer = setTimeout(() => { 
     this.setState({ showMessage: false }) 
     actions.resetUpdatedTagDataSuccessfulFlag() 
     }, 3000) 
    } 
    } 
} 

需要注意的是:

  • 由setTimeout的使用的setState,我已經消除了需要使用forceUpdate()
  • 我使用lodash做一個檢查,看看是否有託從之前的渲染更改爲當前渲染。反應將重新呈現組件出於以下原因之一:
    • 如果道具改變
    • 如果組件的狀態更新
    • 如果父母中的一方需要更新任一兩個原因。 所以我們做一個檢查,看看更新只發生,因爲道具已經改變,如果它已經改變,然後做一個setState顯示消息和設置的超時在3秒後不顯示消息。

這些都只是使用建議。你能告訴我更多關於你用於單元測試的框架嗎?如果是開玩笑,我可能會有所幫助。