class Component extends React.Component { constructor(props) { super(props); this.state = { value: this.props.value }; } render() { return <div>The value is: {this.state.value}</div> } }
如上程式碼所示,僅僅在constructor中將props賦值給state,constructor僅在元件建立時執行一次,props發生變化不會執行,因此,render中的value僅顯示初始值,不會發生變化
如下,在constructor和componentWillReceiveProps都進行props的賦值,才可以完美解決props設定state的問題:
class Component extends React.Component { constructor(props) { super(props); this.state = { value: this.props.value }; } componentWillReceiveProps(nextProps) { if(nextProps.value !== this.props.value) { this.setState({value: nextProps.value}); } } render() { return <div>The value is: {this.state.value}</div> } }
出處:https://segmentfault.com/a/1190000015606509