React总结
[toc]
1.React组件生命周期
1.1 生命周期图
组件的生命周期的图如下:

具体可参考React 组件生命周期
1.2 说明
- 构造函数
constructor(props, context)
在创建组件的时候调用一次。
- componentWillMount
void componentWillMount()
在组件挂载之前调用一次。如果在这个函数里面调用setState,本次的render函数可以看到更新后的state,并且只渲染一次。
- componentDidMount
void componentDidMount()
在组件挂载之后调用一次。这个时候,子主键也都挂载好了,可以在这里使用refs。
- componentWillReceiveProps
void componentWillReceiveProps(nextProps)
props是父组件传递给子组件的。父组件发生render的时候子组件就会调用componentWillReceiveProps(不管props有没有更新,也不管父子组件之间有没有数据交换)。
- shouldComponentUpdate
bool shouldComponentUpdate(nextProps, nextState)
组件挂载之后,每次调用setState后都会调用shouldComponentUpdate判断是否需要重新渲染组件。默认返回true,需要重新render。在比较复杂的应用里,有一些数据的改变并不影响界面展示,可以在这里做判断,优化渲染效率。
- componentWillUpdate
void componentWillUpdate(nextProps, nextState)
shouldComponentUpdate返回true或者调用forceUpdate之后,componentWillUpdate会被调用。
- componentDidUpdate
void componentDidUpdate()
除了首次render之后调用componentDidMount,其它render结束之后都是调用componentDidUpdate。
componentWillMount、componentDidMount和componentWillUpdate、componentDidUpdate可以对应起来。区别在于,前者只有在挂载的时候会被调用;而后者在以后的每次更新渲染之后都会被调用。
2.组件传值
2.1 父组件向子组件传值
相对而言很简单,直接通过组件的参数就可以将父组件的值传递到子组件。
<ExpertMap {...options} />
这里的options就是传递给子组件的值。子组件通过this.props
就可以获得所需的值:
const options = this.props;
2.2 子组件向父组件传值
子组件向父组件传值,主要通过函数来完成,该函数的特点为:
- 在父组件中定义
- 通过组件传值,将该函数从父组件传递到子组件
- 在子组件中被调用(需要传值进去的时候在子组件中将参数值传递进去)
以SingleTrajectory中的为例,
父组件:
<STRightContainer />
它定义了两个函数:
play = () => {
this.setState({ reload: !this.state.reload });
};
changeValues = (value1) => {
const value = {};
for (const v in this.state.value) {
if (v in value1) {
if (value1[v] !== this.state.value[v]) {
value[v] = value1[v];
}
} else {
value[v] = this.state.value[v];
}
}
this.setState({ value });
};
这两个函数主要通过改变state的值来实现组件的更新。同时,将两个函数做了一个封装,封装为一个参数值,这样主要是为了避免传进去的参数过多:
const functions = {
play: this.play,
changeValues: this.changeValues,
};
再通过子组件的调用将值传递到子组件中去,如下。
子组件:<STOperators person={this.props.person} functions={functions} settingValues={settingValues} />
同样,这里通过this.props
获取:
const { functions } = this.props;
const { changeValues } = functions;
const { play } = functions;
这样就完成了子组件向父组件的传值。总结一下:
- 子组件向父组件传值是通过函数调用完成的,该函数定义在父组件中,在子组件中调用
- 函数在子组件中被调用,传递值到父组件中执行,父组件的state被更新,完成了子组件到父组件的传值
2.3 两个相同级别的组件传值
通过上面的介绍,我们可以很容易的实现两个没有直接联系的组件间的传值,主要还是通过他们共同的父组件来完成的,即:
- 子组件向父组件传值
- 父组件state变化
- 另外的子组件根据情况更新
这样就完成了两个不同子组件的传值,当然了可能会有好几层才能实现。