【问题标题】:React component life cycle invoke orderReact 组件生命周期调用顺序
【发布时间】:2016-12-05 23:19:56
【问题描述】:

我是 JavaScript 新手。我最近开始学习 ReactJS 并阅读了有关组件生命周期的内容。我收集到的是,在组件初始化时,循环看起来像这样:

GetDefaultProps -> GetInitialState -> ComponentWillMount -> Render -> ComponentDidMount

我还读到getDefaultProps() 在创建任何实例之前被调用。如果我有以下代码:

class Sample extends React.Component {
    constructor(props) {
        super(props);
        alert("In constructor");
    }
    getDefaultProps() {
        alert("In getDefaultProps");
    }
    render() {
        return <div></div>;
    }
}

React.render(<Sample/>, document.getElementById('app'));

我认为它会警告“在 getDefaultProps 中”,然后是“在构造函数中”。但只有“在构造函数中”被警告。为什么会这样?

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    现在在 es6 类上设置默认 props 的方法是使用 defaultProps 属性

    所以你会做这样的事情:

    class Sample extends React.Component {
        constructor(props) {
            super(props);
            alert("In constructor");
        }
        render() {
            return <div></div>;
        }
    }
    
    Sample.defaultProps = {
       sampleProp: 'sample',
    };
    

    【讨论】:

    • 您的意思是sampleProp: 'sample'?另外,defaultProps 在循环中是否仍然出现在GetInitialState 之前?谢谢。
    • defaultProps 不再是一个函数,因此它在运行时被设置一次。 GetInitialState 也不见了。现在应该使用 this.state = { sampleState: 'sampleState' }; 在构造函数中设置
    【解决方案2】:

    getDefaultProps() 可用于定义可通过 this.props 访问的任何默认道具。

    假设您有一个子组件 Child 并且您在父组件中使用该组件并传递一个 prop 说 testProp="this is test prop"。然后在子组件中它可以用作 this.props.testProps。但是现在的情况是,无论如何您都需要此道具的值,并假设您没有从父组件将此道具发送到子组件。然后在这种情况下 getDefaultProps 将出现,您可以在其中设置该道具的默认值,如果它是由父组件定义的,那么它将用作父组件的值,否则它将使用默认值。

    所以我们可以在 ES5 中为该属性设置默认值:

    getDefaultProps() {
      testProp="This is default value for test prop"
    }
    

    在 ES6 中:

    Sample.defaultProps = {
       testProp: 'This is default value for test prop',
    };
    

    【讨论】:

      【解决方案3】:

      defaultprops 可以使用 static 关键字在类中定义

      static defaultProps = {
         test: "default value of test"
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-11-17
        • 2018-05-21
        • 1970-01-01
        • 2020-05-10
        • 2012-10-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多