生命周期
Mounting(挂载阶段)
-
constructor()
-
加载时调用,初始化state
-
static getDerivedStateFromProps(props, state)
props: 父组件传来的props
state: 本组件的state值
会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容。 -
render()
创建虚拟DOM,进行diff算法 -
componentDidMount
渲染完成,在此函数中调用axios和ajax请求
Updating(更新阶段)
- static getDerivedStateFromProps(props, state)
会在调用 render 方法之前调用,并且在初始挂载及后续更新时都会被调用。它应返回一个对象来更新 state,如果返回 null 则不更新任何内容。 - shouldComponentUpdate(nextProps, nextState)
当 props 或 state 发生变化时,此函数会在渲染执行之前被调用。
返回值默认为 true,更新dom
返回false,阻止更新,不调用render - render()
创建虚拟DOM,进行diff算法 - getSnapshotBeforeUpdate(prevProps, prevState)
最近一次渲染输出(提交到 DOM 节点)之前调用。返回一个值,作为componentDidUpdate的第三个参数
prevProps:更新前的props值
prevState:更新前的state值 - componentDidUpdate()
组件更新完成后调用
Redux
redux的三大原则
- 单一的数据源
- 状态只读
- 状态的修改均有纯函数完成
redux的核心是一个store
-
creatStore(reducers,初始值状态
-
reducers 负责响应action
-
reducer 的职责是根据previousState和action 计算出新state。
-
redux 的核心api 是creatStore()
-
通过creatStore 创建的store 对象,有4个方法
-
getState()获取当前的store
-
dispatch(action)分发action,并返回这个action,这是唯一修改store中数据的方式
-
subscribe(listener)注册一个监听者。他在store发生变化是调用
-
replaceReducer更新当前store里的reducer
Refs
Refs 是使用 React.createRef() 创建的,并通过 ref 属性附加到 React 元素。
- 当 ref 属性用于 HTML 元素时,构造函数中使用 React.createRef() 创建的 ref 接收底层 DOM 元素作为其current 属性。
- 当 ref 属性用于自定义 class 组件时,ref 对象接收组件的挂载实例作为其 current 属性。
- 在componentDidMount函数中通过访问dom让文本框处于激活状态