生命周期
挂载
当组件实例被创建并插入DOM中,生命周期调用顺序如下**
construstor() 只执行一次。初始化,在super之后构建
static getDerivedStateFromProps()
render() 负责渲染,即合成虚拟DOM
componentDidMount() 获取真实DOM比如ajax
更新
当组件的 props 或 state 发生变化时会触发更新。组件更新的生命周期调用顺序如下:
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
卸载
当组件从 DOM 中移除时会调用如下方法:
componentWillUnmount()
错误处理(不常用,一般用console.log)
当渲染过程,生命周期,或子组件的构造函数中抛出错误时,会调用如下方法:
static getDerivedStateFromError()
componentDidCatch()
`是ES6新增的模版字符串
“hello” + str + “world !”
``hello ${str} world !
减少更新次数
方法一:
把Component改成PureComponent,但这种只做了第一层,方法二是更深层的。
方法二:
第一个判断
1 | shouldComponentUpdate(nextProps,nextState){ |
第二个判断
老版本的坑:
constructor里面通过props来初始化一个state,在props修改之后,这个state不会再次更新。需要借助于componentWillReceiveProps来做一次修正
新版本:
1 | constructor(){ |
Ajax
json官网 前后端接口
npm install axios -S
新建 src/services/apis.js
1 | export default{ |
新建src/services/index.js
1 | import axios from 'axios' |
在App.js中引入
1 | import { getTodos } from './services' |
同时
1 | constructor() { |
- 本文作者: Raphael_Li
- 本文链接: https://lifei-2019.github.io/react5/
- 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!