2017-05-24 98 views
1

中將狀態還原爲默認道具時,調用重置時將狀態還原爲默認狀態的最佳方式是什麼?或者另一種解決方案是無縫加載組件(我讀forceUpdate是不是一個好的選擇)使用以下ES6語法在ES6

class XYZ extends React.Component { 
    constructor() { 
    super(), 
    this.state = { 
    ... 
    } 
    } 

    reset() { 
    //I need to revert to default props here 
    } 
} 

XYZ.propTypes = { 
    ... 
} 

XYZ.defaultProps = { 
    ... 
} 

export default XYZ 

技術上,我可以實現諸如復位:

reset() { 
    if (this.mounted) { 
    this.setState(()=> { 
     const newState = { 
     anchorStandards: {writing: [], reading: []}, 
     gradeLevels: {gradeLevels: []} 
     } 
     this.props.onFilterChange(newState) 
     return newState 
    }) 
    } 
} 

但我想知道是否有方法來調用this.defaultPros

回答

0

執行getDefaultState(props)函數,然後在constructor(props)reset()中調用它。

例如:

getDefaultState(props) { 
    return { importantState: props.importantState } 
} 

constructor(props) { 
    this.state = this.getDefaultState(props) 
} 

reset() { 
    this.setState(this.getDefaultState(this.props)) 
} 

通過這種方法,父組件並不需要知道什麼,以及確定相關的道具和初始狀態只能寫一次的代碼。

+0

我用的是XYZ.defaultProps的理由是: warning.js:36警告:getDefaultProps在XYZ上定義,這是一個普通的JavaScript類。這僅支持使用React.createClass創建的類。改用靜態屬性來定義defaultProps。所以你寫的,如果我使用getDefaultState我可以使用該語法 –

+0

嗯,是的。事情是,'getDefaultProps()'存在於舊的React版本中,所以現在它會警告你,因爲它認爲你犯了一個錯誤。 **這就是說,記住**:如果一個Component修改自己的數據(就像你用'reset()'做的那樣,它應該被稱爲'state',而不是'props'.React調用外部給定的信息'道具',以及內部決定的信息'狀態' – slezica

0

試試這個簡單的方法。

https://jsfiddle.net/pablodarde/5fhdLcey/

父元素

class Main extends React.Component { 
    constructor() { 
    super(); 
    this.state = { 
     name: "Pablo", 
    }; 
    this.reset = this.reset.bind(this); 
    } 

    reset() { 
    this.setState({ 
     name: undefined, 
    }); 
    } 

    render() { 
    return(
     <div> 
     <HelloWidget name={this.state.name} reset={this.reset} /> 
     </div> 
    ); 
    } 
}; 

子元素

class HelloWidget extends React.Component { 
    constructor() { 
    super(); 
    } 

    render() { 
    return(
     <div> 
     <h2>{this.props.name}</h2> 
     <button onClick={this.props.reset} >Reset</button> 
     </div> 
    ); 
    } 
} 

HelloWidget.propTypes = { 
    name: React.PropTypes.string, 
    reset: React.PropTypes.func, 
} 

HelloWidget.defaultProps = { 
    name: "Friend", 
}