Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
287 views
in Technique[技术] by (71.8m points)

一次数据更新shouldComponentUpdate却执行两次?

父组件

import React from 'react'
import Child from './Child'


export default class Life extends React.Component{

  state = {
    count: 0
  }

  handleMiu = () => {
    this.setState({
      count: this.state.count - 1
    })
  }

  handleAdd = () => {
    this.setState({
      count: this.state.count + 1
    })
  }


  render() {
    return (
      <div>
        <h2>{this.state.count}</h2>
        <button onClick={this.handleAdd}>+</button>
        <button onClick={this.handleMiu}>-</button>
        <hr/>
        <Child count={this.state.count} />
      </div>
    )
  }
}

子组件

import React from 'react'


export default class Child extends React.Component{

  componentWillMount () {
    console.log('child will mount');
    
  }

  componentDidMount () {
    console.log('child did mount');
  }

  componentWillReceiveProps(newProps) {
    console.log('will receive props ' + newProps.count);
  }

  shouldComponentUpdate() {
    console.log('should update');
    return true
  }

  componentWillUpdate() {
    console.log('will update');
  }

  componentDidUpdate() {
    console.log('did update');
    
  }

  render() {
    return (
      <div>
        <h2>{this.props.count}</h2>
      </div>
    )
  }
}

image
点击相加的按钮,有两次shouldComponentUpdate,componentWillUpdatecomponentDidUpdate却只有一次是什么原因?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你是否开启了严格模式
https://zh-hans.reactjs.org/d...
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...