×

React开发小应用:React里的不可变值

作者:Terry2021.05.08来源:Web前端之家浏览:4172评论:0
关键词:react

分享个React开发小应用:React里的不可变值。

什么是不可变值?

函数式编程是指程序里面的函数和表达式都能像数学中的函数一样,给定了输入值,输出是确定的。比如

let a = 1;
let b = a + 1;
=> a = 1  b = 2;

变量b出现,虽然使用了变量a的值,但是没有修改a的值。

再看我们熟悉的react中的代码,假如初始化了this.state = { count: 1 }

componentDidMount() {
    const newState = { ...state, count: 2 }; // { count: 2 }
    this.setState(newState);
}

虽然我们使用了this.state,但是没有修改this.state的引用地址和直接修改count的值,对待this.props也一样。

为什么使用不可变值

React官网中给出三点好处:

  • 简化复杂的功能

不可变性使得复杂的特性更容易实现。

  • 跟踪数据的改变

如果直接修改数据,那么就很难跟踪到数据的改变。跟踪数据的改变需要可变对象可以与改变之前的版本进行对比,这样整个对象树都需要被遍历一次。

跟踪不可变数据的变化相对来说就容易多了。如果发现对象变成了一个新对象,那么我们就可以说对象发生改变了。

  • 确定在 React 中何时重新渲染

不可变性最主要的优势在于它可以帮助我们在 React 中创建 pure components。我们可以很轻松的确定不可变数据是否发生了改变,从而确定何时对组件进行重新渲染。

React性能优化离不开不可变值

  • 首先,我们都知道,shouldComponentUpdate钩子函数默认返回true,即只要父组件更新,子组件一定更新。

  • shouldComponentUdpate中可以接收两个参数,nextProps和nextState,假如我们通过判断this.props.xxx和nextProps.xxx相等以及this.state.xxx与nextState.xxx相等,可以将返回值设置为false,说明此次并不需要更新子组件。

class CounterButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: 1};
  }

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
  }

  render() {
    return (
      <button
        color={this.props.color}
        onClick={() => this.setState(state => ({count: state.count + 1}))}>
        Count: {this.state.count}
      </button>
    );
  }
}
  • React v15.3新增加了一个PureComponent类,能够对props和state进行浅比较来减少render函数的执行次数,避免不必要的组件渲染,实现性能上的优化。

  • PureComponent是什么原理呢

我们知道JS中的变量类型分为基本类型(number、string、boolean、undefined、null、symbol)和引用类型(function、object、function),基本类型的值保存在栈内存当中,引用类型的值保存在堆内存当中,栈内存中只保存指向堆内存的引用。而浅比较就是只对栈内存中的数据进行比较。

class App extends PureComponent {
  state = {
    items: [1, 2, 3]
  }
  handleClick = () => {
    const { items } = this.state;
    items.pop();
    this.setState({ items });
  }
  render() {
    return (
        <div>
            <ul>
                {this.state.items.map(i => <li key={i}>{i}</li>)}
            </ul>
            <button onClick={this.handleClick}>delete</button>
        </div>
    )
  }
}

上边这个例子使用了PureComponent,而且只改变了数组items里的值,而没改变items的引用地址,所以认为items没有发生变化,不会触发render函数,不会触发组件的渲染。

如果想实现组件更新,可以按如下的方式,创建一个新的数组,将新数组的地址赋给items。

handleClick = () => {
    const { items } = this.state;
    items.pop();
    var newItem = [...items];
    this.setState({ item: newItem });
}

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/react20210508a2.html

网友评论文明上网理性发言 已有0人参与

发表评论: