javascript - getDefaultProps 和 getInitialState 之间有什么区别?

标签 javascript reactjs

我是 React js 的新手。

getDefaultProps () {
    return {
        backgroundColor: 'gray',
        height: 200,
        width: 200
    }
},

我为 getDefaultPropsgetInitialState 设置了相同的值:

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/

相关文章:

javascript - ReactJS - child 如何访问它是 parent 的 Prop ?

reactjs - 如何从 React 中的对象中获取数据

reactjs - 两种方式的数据绑定(bind)不适用于 React 中动态加载的多个复选框

javascript - 在 javascript 中使用 post 方法时遇到问题

javascript - 当函数已经捕获错误时知道异步函数是成功还是失败?

Javascript:在添加 CSS 样式的同时遍历数组

php - Laravel PATCH 请求不读取 Axios 表单数据

javascript - 使用 javascript 从一页到 div 的 HTML

javascript - ui-calendar 首先隐藏然后显示时的问题

javascript - 在React组件中,如何在clickabel中制作<span>并调用该React组件的函数?