react生态基本使用笔记

1.使用react-router的link标签的时候可以这样使用:

1
<Link to={{ pathname: `routeUrl`, state: stateObj }}>target</Link>

Link里面所传递的state对象在子页面中可以通过this.props.location.state来进行获取。一个好处,放在location里面的数据不会被刷新掉。

2.更新过程不会触发componentWillMount以及componentDidMount。

3.一个route形如下面这样的话:,那么我们可以在CourseClassInfo组件中通过this.props.params.classId来获取班级id。

4.React挂载阶段所触发的生命周期方法:

  • constructor()
  • componentWillMount()
  • render()
  • componentDidMount()

需要注意的地方,React 16.3版本发布以后,引入了下面几个生命周期方法:UNSAFE_componentWillMount,UNSAFE_componentWillReceiveProps,UNSAFE_componentWillUpdate,这几个方法是用来替代componentWillMount和componentWillReceiveProps以及componentWillUpdate的,为什么要进项替代?因为这几个方法在接下来react主要希望实现的目标-异步渲染中将会带来比之前更大的误解。 虽然在react 16.3版本中引入了这几个方法,但是旧的原有方法和新的替代方法是处于一个可以共存的状态下。

来到react 17以上的版本之后,react将componentWillMount,componentWillReceiveProps,componentWillUpdate这些旧方法都给移除了。只有这些方法相对应的带有UNSAFE_前缀的才可使用。

5.更新阶段执行的生命周期方法:首先更新一个组件有三种途径,分别是父组件更新,自身状态变化,自身强制更新。不同的途径所触发的生命周期方法是不同的,先介绍父组件更新所触发的生命周期方法:

  • 1.componentWillReceiveProps()
  • 2.shouldComponentUpdate()
  • 3.componentWillUpdate()
  • 4.render()
  • 5.componentDidUpdate()

当自身状态发生变化的时候,也就是自己调用setState,此时触发的生命周期方法如下所示:

  • 1.shouldComponentUpdate()
  • 2.componentWillUpdate()
  • 3.render()
  • 4.componentDidUpdate()

当调用forceUpdate()强制触发更新的时候,将会触发下面这些生命周期方法:

  • 1.componentWillUpdate()
  • 2.render()
  • 3.componentDidUpdate()

6.卸载阶段:这个阶段调用的就是componentWillUnmount,可以在这个方法里面执行一些垃圾回收操作。