javascript - 为什么这个应用程序中的大部分组件每秒都在更新?
问题描述
在以下代码中,setInterval
将切换更新为in 中的true
每一秒。然而,就 React 而言,切换状态并没有真正改变,因为它一直被设置为相同的值......据我所知,React 在决定是否更改之前检查相关的状态值以查看它们是否已更改/更新是否重新渲染 UI 视图。那么为什么要更新任何组件呢?componentDidMount
App
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;
解决方案
this.setState({ toggle: true });
当您在此处设置状态时,您会触发 App 组件中的重新渲染。这是因为你的新状态是一个不同的对象。即使它具有相同的值(切换:真),对象也是不同的。因此应用程序的渲染方法将被调用,因此子项将被再次渲染。
如果您不想更新某些子项,可以使用PureComponent或备忘录挂钩。基本上,他们是在做一个浅层的比较来比较道具。
推荐阅读
- c# - 将内容数量有限的字符串数组内容从最后一个数组位置转移到新的字符串数组
- android - 我们如何将菜单设置为工具栏
- c++ - 如何使用 std::copy_n 打印出 std::vector 的内容?
- mysql - 如何在 JOIN 查询中使用 COUNT() 获取数据行
- android - -TextView 太长时布局中断
- pandas - ImportError:没有名为 pandas [pycharm] python 3.7 的模块
- slurm - 如何在负载最少的节点上运行作业?
- excel - VBA UserForm 设计,如何有效管理控件的层级?
- reactjs - 如何在 React 中使用 FileReader?(得到一个奇怪的错误)
- javascript - 如何使用数据库表中的特定 ID 或变量登录