聲明周期與組件卸載
- props配置:使用組件時傳入數據
- state私有數據:組件內部使用的數據
state的使用注意事項
- 必須使用setState方法來更改state
- 多個setState會合并調用
- props和state更新數據要謹慎(有可能在異步程序中更新)
- setState操作合并的原理:淺合并,即設置什么屬性就更新什么,最終再合并成一個state
// 不要這樣去更新
this.setState({result: this.state.result + this.props.content
})
// 使用這種方式
this.setState((state, props) => {// state 上一個state// porps 此次更新時被使用的propsstate.result = state.result + props.content
})
// 設置arr,用一個全新的數組替換,而不再使用原先的引用
this.setState({arr: [...this.state.arr, 4]// or用數組的concat方法返回新數組
})
- state是組件內部特有的數據封裝
- 其他組件無法讀寫該組件的state
- 組價可以通過其他組件調用時傳入的屬性來傳遞state的值
- props雖然是響應式的,但在組件內部是只讀的
- state只能傳遞給自己的子組件(state的安全影響范圍)
- 組件可以沒有狀態
- 組件有無狀態可以切換(原先無狀態,在生命周期函數/綁定的時間處理函數中增加狀態)
- 總結:這種數據(狀態)從父到子,由上而下傳遞的方式叫單向數據流
class MyTime extends React.Component {constructor(props) {super(props)}state = {time: new Date().toString()}// 組件已經被渲染到了DOM中,運行的函數componentDidMount() {this.t = setInterval(() => {this.setState({time: new Date().toString()})}, 1000)}// 組件即將被卸載時componentWillUnmount() {clearInterval(this.t)this.t = nullconsole.log('over')}render() {return (<div><h1>{this.state.time}</h1></div>)}
}
ReactDOM.render(<MyTime />,document.getElementById('app')
)
setTimeout(() => {ReactDOM.unmountComponentAtNode(document.getElementById('app'))
}, 3000)