概览
- React 的组件可以定义为 class 或函数的形式
- 如需定义 class 组件,需要继承 React.Component
- 在 React.Component 的子类中有个必须定义的 render() 函数
- 强烈建议不要创建自己的组件基类;在 React 组件中,代码重用的主要方式是组合而不是继承。
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
组件的生命周期
- 挂载:当组件实例被创建并插入 DOM 中时,其生命周期调用顺序如下:
- constructor()
- static getDerivedStateFromProps()
- render()
- componentDidMount()
- 更新: 当组件的 props 或 state 发生变化时会触发更新。组件更新的生命周期调用顺序如下:
- static getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBedoreUpdate()
- componentDidUpdate()
- 卸载:当组件从 DOM 中移除时会调用如下方法:
- componentWillUnmount()
- 错误处理:当渲染过程,生命周期,或子组件的构造函数中抛出错误时,会调用如下方法:
- static getDerivedStateFromError()
- componentDidCatch()
render()
- render() 方法是 class 组件中唯一必须实现的方法
- 当 render 被调用时,它会检查 this.props 和 this.state 的变化并返回以下类型之一:
- React元素
- 数组 或 fragements
- Portals
- 字符串 或 数值类型
- 布尔类型 或 null
- render() 函数应该为纯函数,这意味着在不修改组件 state 的情况下,每次调用时都返回相同的结果
constructor()
- 如果不初始化 state 或不进行方法绑定,则不需要为 React 组件实现构造函数。
- 通常,在 React 中,构造函数仅用于以下两种情况:
- 初始化 state
- 为事件处理函数绑定实例
- 应在其他语句之前调用 super(props)。否则,this.props 在构造函数中可能会出现未定义的 bug。
- 注意:避免将 props 的值复制给 state!
constructor(props) { super(props); // 不要在这里调用 this.setState() this.state = { counter: 0 }; this.handleClick = this.handleClick.bind(this); }
componentDidMount()
- 会在组件挂载后(插入 DOM 树中)立即调用
- 依赖于 DOM 节点的初始化应该放在这里
- 也可以用于通过网络请求获取数据、添加订阅
componentDidMount()
componentDidUpdate()
componentDidUpate