constructor(props)
React组件的构造函数在挂载之前被调用。
在实现 react.Component 构造函数时,应在其他语句之前(添加其他内容前),调用 super(props) ,用来将父组件传过来的 props 绑定在这个类中,使用 this.props 将会得到。
通常,在React中,构造函数仅用于一下两种情况:
- 通过给this.state赋值对象来初始化内部state
- 为事件处理函数绑定实例
constructor(props: P) {super(props)console.log('constructor',this)// 定义statethis.state = {name: 'syukinmei'}// 普通函数的this绑定,解决普通函数this丢失指向的事件源DOM是虚拟DOMundefinedthis.handler=this.handler.bind(this)}handler(){console.log(this)}
static getDerivedStateFromProps(nextProps,prevState)
componentDidMount()
componentDidMount() {console.log('componentDidMount', this)// 将虚拟DOM渲染成真实DOM,获得真实DOM对其进行操作this.P.style.background = "red"// 发生数据请求fetch('http://59.110.226.77:3000/api/category').then(data => data.json()).then(ref => console.log(ref)).catch(error => Promise.reject(error))}P: any = {}render() {return (<div><p ref={el => this.P = el}>{this.state.name}</p></div>)}
