我是 React js 的新手。
getDefaultProps () {
return {
backgroundColor: 'gray',
height: 200,
width: 200
}
},
我为 getDefaultProps
和 getInitialState
设置了相同的值:
getInitialState () {
return {
backgroundColor: 'gray',
height: 200,
width: 200
}
},
两者之间的逻辑区别是什么。应该覆盖哪个或哪个将首先执行。
谢谢。
最佳答案
获取初始状态
- 对象
**getInitialState()**
在组件被调用之前调用一次 安装。返回值将作为初始值 这个.state.
Note: This method is not available on ES6 class components that extend React.Component. For more information, please read our documentation about ES6 classes.
getDefaultProps
- 对象
**getDefaultProps()**
类调用一次并缓存 被 build 。映射中的值将在 this.props 上设置,如果 prop 不是由父组件指定的(即使用 in 检查)。 - 此方法在创建任何实例之前调用,因此
不能依赖 this.props。此外,请注意,任何复杂的
getDefaultProps()
返回的对象将被共享 实例,未复制。
关于javascript - getDefaultProps 和 getInitialState 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40133535/