[英]React component life cycle invoke order
我是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'));
我以为它会提示“ In getDefaultProps”,然后提示“ In Constructor”。 但是只有“在构造函数中”被警告。 为什么会这样呢?
现在在es6类上设置默认道具的方法是使用defaultProps属性
因此,您需要执行以下操作:
class Sample extends React.Component {
constructor(props) {
super(props);
alert("In constructor");
}
render() {
return <div></div>;
}
}
Sample.defaultProps = {
sampleProp: 'sample',
};
getDefaultProps()可用于定义可通过this.props访问的任何默认prop。
假设您有一个子组件Child,并且您正在父组件中使用该组件,并传递一个道具,说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',
};
可以在类中使用static关键字定义defaultprops
static defaultProps = {
test: "default value of test"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.