2017-07-19 216 views
2

我有一個類,ElementBuilder下面,當用戶保存他們已經建立的Element,我希望狀態重置爲下面的值。在React + ES6中重置初始狀態

我有這個類中的一些功能,我沒有提供,但改變了title,sizecolor的狀態。

在ES 5中,我將在我的課上有一個getInitialState函數,並且可以在函數中調用this.getInitialState()

此元素位於我的應用程序中,用於登錄用戶的生命週期,我希望默認值始終保持相同,無論過去的用法如何。

如何在不寫入設置默認值對象的函數的情況下實現此目的(或許這就是答案)?謝謝!

class ElementBuilder extends Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
      title: 'Testing, 
      size: 100, 
      color: '#4d96ce', 
     }; 
    } 

    resetBuilder() { 
     this.setState({ this.getInitialState() }); 
    } 
} 
+3

您可以隨時定義與初始值類的常量之外。然後用它來初始化狀態並在任何給定時間重置。 – Crysfel

+0

針對狀態管理的功能強大請使用redux查看[redux](http://redux.js.org/),您可以做各種事情,例如撤消,重做和時間旅行努力 – sachgits

回答

2

你可以使用一個getter函數:

class ElementBuilder extends Component { 
    constructor(props) { 
     super(props); 

     this.state = this.initialState; 
    } 

    get initialState() { 
     return { 
      title: 'Testing', 
      size: 100, 
      color: '#4d96ce', 
     }; 
    } 

    resetBuilder() { 
     this.state(this.initialState); 
    } 
} 

,或只是一個變量:

constructor(props) { 
    super(props); 

    this.initialState = { 
     title: 'Testing', 
     size: 100, 
     color: '#4d96ce', 
    }; 
    this.state = this.initialState; 
} 
+1

getter函數仍然是一個函數;) –

+0

@FelixKling哦,我錯過了「沒有寫入函數」:)但第二個選項看起來不錯。 –

+0

這很好。感謝米哈伊爾和菲利克斯! –

1

由於初始狀態似乎並不依賴於任何具體的實例,只要定義課外價值:

class initialState = {...}; 

class ElementBuilder extends Component { 
    constructor(props) { 
     super(props); 

     this.state = initialState; 
    } 

    resetBuilder() { 
     this.setState(initialState); 
    } 
} 
0

使用的高順序組件,清除組件的狀態(重新呈現)

爲例Element.jsx:

// Target ----- // 

class Element extends Component { 

    constructor(props){ 
    super(props) 
    const { 
     initState = {} 
    } = props 
    this.state = {initState} 
    } 

    render() { 
    return (
     <div className="element-x"> 
      {...} 
     </div> 
    ) 
    } 
} 

// Target Manager ----- // 

class ElementMgr extends Component { 

    constructor(props){ 
     super(props) 
     const { 
      hash = 0 
     } = props 
     this.state = { 
      hash, // hash is a post.id 
      load: false 
     } 
    } 

    render() { 
     const {load} = this.state 
     if (load) { 
      return (<div className="element-x"/>) 
     } else { 
      return (<Element {...this.props}/>) 
     } 
    } 

    componentWillReceiveProps(nextProps) { 
     const {hash = 0} = nextProps 
     if (hash !== this.state.hash) { 
      this.setState({load:true}) 
      setTimeout(() => this.setState({ 
       hash, 
       load:false 
      }),0) 
     } 
    } 
} 

export default ElementMgr