這個問題,困擾了我,特此記錄。
子組件顯示父組件傳來的props 做更新有 以下2種常用方式:
1.直接使用
class Child extends Component { render() { return <div>{this.props.someThings}</div> } }
這種方式可以直接在子組件中使用,方便快捷,父組件的更新的數據直接影響子組件的值。
2.轉換成自己的state
class Child extends Component { constructor(props) { super(props); this.state = { someThings: props.someThings }; } componentWillReceiveProps(nextProps) { this.setState({someThings: nextProps.someThings}); } render() { return <div>{this.state.someThings}</div> } }
自己在構造函數中初始化一個值,在將 status 通過 componentWillReceiveProps 生命周期方法 更新
自己喜歡用的是第二種,看起來易維護,代碼結構清晰
但是,我遇到一個問題,是在渲染第一次是正常的,之后怎么也不做渲染了
后面發現了,是無意間使用了 提升react加載性能的 shouldComponentUpdate方法,該方法會阻止 states 的重新渲染
無狀態的函數聲明組件,如何實現呢,正在解決中。。。
