一、安装
第一步
npm install -g create-react-app
构建项目
create-react-app your-app 注意命名方式(命名不能有大写字母)
或者 npx create-react-app your-app (这种要求node在5.0版本以上,npx为npm自带命令)
下载完成之后
cd your_app
npm run start 或者 yarn start
运行之后一个简单的项目基本上构建完成,后面根据个人需要下载依赖
二、生命周期
初始化
在组件初始化阶段会执行
1、constructor //完成react数据初始化
2、static getDerivedStateFromProps()
3、componentWillMount() / UNSAFE_componentWillMount() //组件已经完成初始化数据,但是还未渲染DOM是执行的逻辑,主要用于服务端渲染
4、render() //渲染
5、componentDidMount() //组件第一次渲染执行的逻辑,dom节点已经生成
componentWillMount已经不建议使用,可以使用 UNSAFE_componentWillMount。
在初始化过程中componentDidMount只会执行一次。
更新阶段
props 或者state 发生更新会引起组件的更新,组件重新渲染过程中调用一下方法
1、componentWillReceiveProps(nextProps) / UNSAFE_componentWillReceiveProps() //接收父组件新的props,重新渲染组件执行的逻辑
2、static getDerivedStateFromProps()
3、shouldComponentUpdate(nextProps,nextState) //在setState以后,state发生变化,组件会进行重新渲染的流程时执行的逻辑。true继续执行渲染,false阻止更新
4、componentWillUpdate() / UNSAFE_componentWillUpdate()
5、render()
6、getSnapshotBeforeUpdate()
6、componentDidUpdate(prevProps,prevState)
同样componentWillReceiveProps 和 componentWillUpdate 不建议继续使用。
UNSAFE_componentWillReceiveProps在调用的时候会传一个新的参数 newprops,这个参数就是更新后数据,在这个方法中我们进行操作。
卸载阶段
这个阶段执行componentWillUnmount周期函数,通常可以用来销毁定时器、dom节点之类。
在react16.4版本以后,使用getDerivedStateFromProps代替了旧的componentWillReceiveProps及componentWillMount。使用getSnapshotBeforeUpdate代替了旧的componentWillUpdate。
具体原因如下:使用getDerivedStateFromProps(nextProps, prevState)的原因:
旧的React中componentWillReceiveProps方法是用来判断前后两个 props 是否相同,如果不同,则将新的 props 更新到相应的 state 上去。在这个过程中我们实际上是可以访问到当前props的,这样我们可能会对this.props做一些奇奇怪怪的操作,很可能会破坏 state 数据的单一数据源,导致组件状态变得不可预测。
而在 getDerivedStateFromProps 中禁止了组件去访问 this.props,强制让开发者去比较 nextProps 与 prevState 中的值,以确保当开发者用到 getDerivedStateFromProps 这个生命周期函数时,就是在根据当前的 props 来更新组件的 state,而不是去访问this.props并做其他一些让组件自身状态变得更加不可预测的事情。
使用getSnapshotBeforeUpdate(prevProps, prevState)的原因:
在 React 开启异步渲染模式后,在执行函数时读到的 DOM 元素状态并不总是渲染时相同,这就导致在 componentDidUpdate 中使用 componentWillUpdate 中读取到的 DOM 元素状态是不安全的,因为这时的值很有可能已经失效了。
而getSnapshotBeforeUpdate 会在最终的 render 之前被调用,也就是说在 getSnapshotBeforeUpdate 中读取到的 DOM 元素状态是可以保证与componentDidUpdate 中一致的。
不懂得可以查看原网站链接 React 生命周期详细解析及新旧对比
三、react组件声明
react组件通常分为两种声明方式,一种是class类组件,另一种就是函数组件
类组件声明
import React, { Component } from 'react';
class BasicLayout extends Component {
super(props);
this.state={
... //这里面是要声明的默认属性
}
this.handleClick = this.handleClick.bind(this);
}
export default BasicLayout ;
或者第二种方式声明函数组件
import React, { Component } from 'react';
class BasicLayout extends Component {
state={
... //这里面是要声明的默认属性
}
}
export default BasicLayout ;
函数组件声明
const Demo = (props)=>{
props为父组件传过来的参数,等同于 类组件中this.props
}