首页 > 解决方案 > 为什么这个应用程序中的大部分组件每秒都在更新?

问题描述

在以下代码中,setInterval将切换更新为in 中的true每一秒。然而,就 React 而言,切换状态并没有真正改变,因为它一直被设置为相同的值......据我所知,React 在决定是否更改之前检查相关的状态值以查看它们是否已更改/更新是否重新渲染 UI 视图。那么为什么要更新任何组件呢?componentDidMountApp

import React from 'react';

class Pure extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      update: props.toggle,
    };
  }

  render() {
    return (
      <strong>
        <span style={{ color: 'mediumseagreen' }}>Pure: </span>
        {new Date().getSeconds().toString()}
      </strong>
    );
  }
}

const Stateless = props => (
  <strong>
    <span style={{ color: 'orange' }}>Stateless: </span>
    {new Date().getSeconds().toString()}
  </strong>
);

class Normal1 extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      update: props.toggle,
    };
  }

  render() {
    return (
      <strong>
        <span style={{ color: 'dodgerblue' }}>Normal1: </span>
        {new Date().getSeconds().toString()}
      </strong>
    );
  }
}

class Normal2 extends React.Component {
  state = {
    update: this.props.toggle,
  };

  render() {
    return (
      <strong>
        <span style={{ color: 'green' }}>Normal2: </span>
        {new Date().getSeconds().toString()}
      </strong>
    );
  }
}

class Normal3 extends React.Component {
  render() {
    return (
      <strong>
        <span style={{ color: 'red' }}>Normal3: </span>
        {new Date().getSeconds().toString()}
      </strong>
    );
  }
}

class App extends React.Component {
  state = { toggle: true };

  componentDidMount() {
    setInterval(() => {
      this.setState({ toggle: true });
      // this.setState({ toggle: !this.state.toggle })
    }, 1000);
  }

  render() {
    const { toggle } = this.state;
    return (
      <div>
        <Pure toggle={toggle} />
        <br />
        <Stateless toggle={toggle} />
        <br />
        <Normal1 toggle={toggle} />
        <br />
        <Normal2 toggle={toggle} />
        <br />
        <Normal3 />
        <br />
      </div>
    );
  }
}

export default App;

标签: javascriptreactjs

解决方案


this.setState({ toggle: true });

当您在此处设置状态时,您会触发 App 组件中的重新渲染。这是因为你的新状态是一个不同的对象。即使它具有相同的值(切换:真),对象也是不同的。因此应用程序的渲染方法将被调用,因此子项将被再次渲染。

如果您不想更新某些子项,可以使用PureComponent备忘录挂钩。基本上,他们是在做一个浅层的比较来比较道具。


推荐阅读