声明周期与组件卸载
- 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)