Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react 默认props的设置与生命周期函数 #19

Open
GRPdream opened this issue May 29, 2019 · 0 comments
Open

react 默认props的设置与生命周期函数 #19

GRPdream opened this issue May 29, 2019 · 0 comments

Comments

@GRPdream
Copy link
Owner

GRPdream commented May 29, 2019

默认props的设置

react 中组件使用state中的值的时候,允许设置其默认值。

  class Greeting extends React.Component {
     render() {
        return (
           <h1>Hello, {this.props.name}. and  my age is {this.props.age}</h1>
                );
            }
        }
     Greeting.defaultProps = {    
         name: '我是props的默认值!'
         age: 18
         };
      ReactDOM.render(
          <Greeting />,
             document.getElementById('example')
        );

这里没设置 name 的值所以调用的是默认值,如果设置了则会使用设置的值

生命周期函数

value description
constructor 在组件初始化阶段使用的构造函数
componentWillMount 在组件挂载到DOM前调用,且只会被调用一次,在这边调用this.setState不会引起组件重新渲染,也可以把写在这边的内容提前到constructor()中,所以项目中很少用。
render 根据组件的propsstate渲染函数
componentDidMount 组件挂载到DOM后调用,且只会被调用一次
componentWillReceiveProps(nextProps) 此方法只调用于props引起的组件更新过程中,参数nextProps是父组件传给当前组件的新props。但父组件render方法的调用不能保证重传给当前组件的props是有变化的,所以在此方法中根据nextProps和this.props来查明重传的props是否改变,以及如果改变了要执行啥,比如根据新的props调用this.setState出发当前组件的重新render
shouldComponentUpdate(nextProps, nextState) 此方法通过比较nextProps,nextState及当前组件的this.props,this.state,返回true时当前组件将继续执行更新过程,返回false则当前组件更新停止,以此可用来减少组件的不必要渲染,优化组件性能。
componentWillUpdate(nextProps, nextState) 此方法在调用render方法前执行,在这边可执行一些组件更新发生前的工作,一般较少用
componentDidUpdate(prevProps, prevState) 此方法在组件更新后被调用,可以操作组件更新的DOM,prevProps和prevState这两个参数指的是组件更新前的props和state
componentWillUnmount 此方法在组件被卸载前调用,可以在这里执行一些清理工作,比如清楚组件中使用的定时器,清楚componentDidMount中手动创建的DOM元素等,以避免引起内存泄漏

fiber 版本之前

image

fiber 版本之后

image

组件更新有两类情况:
1.父组件重新 render
2.使用 setState

参考文章

详解React生命周期

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant