React原理揭秘(React学习笔记_07)

React原理揭秘

  • 1,setState()
  • 2,JSX语法的转换过程
  • 3,组件更新机制
  • 4,组件性能优化

1,setState()方法

  • setState()是异步更新数据的
state = {
  count: 0
}
this.setState({
  count: this.state.count + 1
})
console.log(this.state.count)  // 1
  • 可以多次调用setState(),只会触发一次render重新渲染页面
class App extends React.Component {
  state = {
    count: 0
  }
  handleAdd = () => {
    this.setState({
      count: this.state.count + 1
    })
    console.log(this.state.count)  // 0
    this.setState({
      count: this.state.count + 1
    })
    console.log(this.state.count)  // 0
  }
  render() {
    console.log('只会执行一次')
    return (
      
哈哈哈: {this.state.count}
) } }
  • 推荐使用setState((state props) => {}) 语法,state表示最新的state,props表示最新的props。也是异步的
 handleAdd = () => {
  // this.setState({
  //   count: this.state.count + 1
  // })
  // console.log(this.state.count)  // 0
  // this.setState({
  //   count: this.state.count + 1
  // })
  // console.log(this.state.count)  // 0
  // 推荐语法, 这种语法也是异步的,
  this.setState((state, props) => {
    return {
      count: state.count + 1
    }
  })
  this.setState((state, props) => {
    console.log('第二次调用====>', state)
    return {
      count: state.count + 1
    }
  })
}
image
  • 在状态更新(页面完成重新渲染)后立即执行某个操作,可以给this.setState()添加第二个参数,语法:
this.setState((state, props) => {

}, () => {})
class App extends React.Component {
  state = {
    count: 0
  }
  handleAdd = () => {
    this.setState((state, props) => {
      return {
        count: state.count + 1
      }
    }, () => {
      console.log('状态更新完成:', this.state.count)  // 1
      console.log(document.getElementById('title').innerText)  // 数值:1
    })
  }
  render() {
    return (
      
数值: {this.state.count}
) } }
image

2,JSX语法的转换过程

JSX是createElement()方法的语法糖(简化语法)

JSX语法会被@babel/preset-react插件编译为createElement()方法

最终会被转换成React元素,React元素是用来描述在屏幕上看到的内容

JSX语法实现:

const ele = (
  

Hello JSX

)

createElement()语法:

const ele = React.createElement('h1', {className: 'greet'}, 'Hello JSX')

React()元素:

const ele = {
  type: 'h1',
  props: {
    className: 'greet',
    children: 'Hello JSX'
  }
}

3,组件更新机制

  • setState()的两个作用:1,修改state 2,更新组件(UI)
  • 过程:父组件重新渲染的时候,也会更新渲染子组件。但只会渲染当前组件子树(当前组件和他所有的子组件)

4,组件性能优化

  • 1,减轻state:只存储跟组件渲染相关的数据
    • 不用做渲染的数据不要放在state中,比如定时器ID等
    • 对于这种需要在多个方法中用到的数据,应该放在this中
class Hello extends React.Component{
  componentDidMount() {
    this.timerId = setInterval(() => {}, 2000)
  }
  
  componentWillUnmont() {
    clearInterval(this.timerId)
  }
}
  • 2,避免不必要的重新渲染
  • 组件更新机制:父组件更新会引起子组件被更新,这种思路很清晰,问题:子组件没有任何变化的时候也会更新渲染,如何避免不必要的重新渲染呢?使用钩子函数shouldComponentUpdate(nextProps, nextState)

其作用是通过返回值决定该组件是否重新渲染,返回true表示重新渲染,false表示不重新渲染。

触发时机:更新阶段的钩子函数,组件重新渲染前执行(shouldComponentUpdate -> render)

class Hello extends React.Component{
  shouldComponentUpdate(nextProps, nextState) {
    // nextProps, nextState都是最新的数据
    return true/false  // 根据条件决定是否重新渲染组件
  }
}

你可能感兴趣的:(React原理揭秘(React学习笔记_07))