我是靠谱客的博主 单纯自行车,这篇文章主要介绍React优化子组件render的使用,现在分享给大家,希望可以做个参考。

在react中,父组件的重新render会引发子组件的重新render,但是一些情况下我们会觉得这样做有些多余,比如:

  1. 父组件并未传递props给子组件
  2. 新传递的props渲染结果不变
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class A extends React.Component { render() { console.log('render') return <div>这是A组件</div> } } class Main extends React.Component { render() { return ( <div> // 点击button会让A不断调用render <button onClick={() => this.setState({ a: 1 })}>Main</button> <A /> </div> ) } }

为了解决这个问题,需要分为ES6类组件和函数式组件两种:

类组件

使用shouldComponentUpdate来对props和state进行判断以此决定是否进行render

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class A extends React.Component { shouldComponentUpdate(nextProps, nextState) { //两次props对比 return nextProps.a === this.props.a ? false : true } render() { console.log('render') return <div>这是A组件</div> } } class Main extends React.Component { // ... render() { return ( <div> <button onClick={() => this.setState({ a: 1 })}>Main</button> <A a={this.state.a} /> </div> ) } }

通过返回false来跳过这次更新

使用React.PureComponent,它与React.Component区别在于它已经内置了shouldComponentUpdate来对props和state进行浅对比,并跳过更新

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//PureComponent class A extends React.PureComponent { render() { console.log('render') return <div>这是A组件</div> } } class Main extends React.Component { state = { a: 1 } render() { return ( <div> <button onClick={() => this.setState({ a: 1 })}>Main</button> <A a={this.state.a} /> </div> ) } }

函数组件

使用高阶组件React.memo来包裹函数式组件,它和类组件的PureComponent类似,也是对对props进行浅比较决定是否更新

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const A = props => { console.log('render A') return <div>这是A组件</div> } // React.memo包裹A const B = React.memo(A) const Main = props => { const [a, setA] = useState(1) console.log('render Main') return ( <div> // 通过setA(a + 1)让父组件重新render <button onClick={() => setA(a + 1)}>Main</button> // 一直传入相同的props不会让子组件重新render <B a={1} /> </div> ) }

它的第二个参数接受一个两次props作为参数的函数,返回true则禁止子组件更新

其他

上面提到的浅比较就是根据内存地址判断是否相同:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// extends React.Component class A extends React.Component { render() { console.log('render A') console.log(this.props) return <div>这是组件A</div> } } class Main extends React.Component { test = [1, 2, 3] render() { console.log('render Main') return ( <div> <button onClick={() => { // 父组件render this.setState({}) this.test.push(4) }} > Main </button> <A test={this.test} /> </div> ) } }

结果是:

使用React.component:


使用React.PureComponent:

使用React.component,点击之后子组件重新render。改为React.PureComponent之后,点击button子组件并不会render。也因此,PureComponent根据前后内存地址判断是否相等,所以向子组件传递函数作为props时,使用内联箭头函数的形式将会导致子组件的重新render;所以可以用箭头函数作为成员变量的形式再将函数引用作为props传递。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持靠谱客。

最后

以上就是单纯自行车最近收集整理的关于React优化子组件render的使用的全部内容,更多相关React优化子组件render内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(151)

评论列表共有 0 条评论

立即
投稿
返回
顶部