企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### 装载过程 组件在装载过程时,也就是当组件第一次被渲染的时候,会触发5个钩子函数: 1. getDefaultProps() 设置默认的props,也可以用dufaultProps设置组件的默认属性。 2. getInitialState() 在使用es6的class语法时是没有这个钩子函数的,可以直接在constructor中定义this.state。此时可以访问this.props。 3. componentWillMount() 组件初始化时只调用,以后组件更新不调用,整个生命周期只调用一次,此时可以修改state。 4. render() react最重要的步骤,创建虚拟dom,进行diff算法,更新dom树都在此进行。此时就不能更改state了。 5. componentDidMount() 组件渲染之后调用,可以通过this.getDOMNode()获取和操作dom节点,只调用一次。 #### 1. constructor 并不是每个组件都需要定义自己的构造函数,无状态的React组件往往就不需要定义构造函数。一个React组件需要构造函数,往往是为了下面的目的是初始化state。 通常写为: ```js constructor(props) { super(props) this.state = { name: props.name, age: 18 } } ``` #### 2. getInitialState 和 getDefaultProps getInitialState 和 getDefaultProps只在使用 `React.createClass` 定义的组件中有用, 在 ES6 的语法定义中 getInitialState 和 getDefaultProps 两个方法根本不会用到。 要初始化 state 只需放到 constructor 中,要初始化 props 只需要使用类方法 defaultProps,比如: ``` class Sample extends React.Component { constructor(props) { super( props); this.state = { foo: 'bar' }; } }); Sample.defaultProps = { return { sampleProp: 0 } }; ``` #### 3. render render函数无疑是React组件中最重要的函数,一个React组件可以忽略其他所有函数都不实现,但是一定要实现render函数,因为所有React组件的父类React.Component类对除render之外的生命周期函数都有默认实现。 当然,某些特殊组件的作用不是渲染界面,或者,组件在某些情况下选择没有东西可画,那就让render函数返回一个null或者false,等于告诉React,这个组件这次不需要渲染任何DOM元素。 需要注意,render函数应该是一个纯函数,完全根据this.state和this.props来决定返回的结果,而且不要产生任何副作用。在render函数中去调用this.setState毫无疑问是错误的,因为一个纯函数不应该引起状态的改变。 #### 4. componentWillMount 和 componentDidMount 在装载过程中,componentWillMount会在调用render函数之前被调用,component-DidMount会在调用render函数之后被调用。 需要注意的是,render函数被调用完之后,componentDidMount函数并不是会被立刻调用,componentDidMount被调用的时候,render函数返回的东西已经引发了渲染,组件已经被“装载”到了DOM树上。