本篇是译文,原文是 Improve Your React App Performance by Using Throttling and Debouncing
引言
使用 React 构建应用程序时,我们总是会遇到一些限制问题,比如大量的调用、异步网络请求和 DOM 更新等,我们可以使用 React 提供的功能来检查这些。
在这篇文章中,我们将研究如何在不使用 React 提供的功能下来改进 React 应用程序性能,我们将使用一种不仅仅适用于 React 的技术:节流(Throttle)和防抖(Debounce)。
从一个例子开始
例子 1
下面这个例子可以很好的解释节流和防抖带给我们的好处,假设我们有一个 autocomp
组件
import React from 'react';import './autocomp.css';from 'react';
import './autocomp.css';
class autocomp extends React.Component { constructor(props) { super(props); this.state= { results: [] } }
constructor(props) {
super(props);
this.state= {
results: []
}
}
handleInput = evt => { const value = evt.target.value fetch(`/api/users`) .then(res => res.json()) .then(result => this.setState({ results: result.users })) }
const value = evt.target.value
fetch(`/api/users`)
.then(res => res.json())
.then(result => this.setState({ results: result.users }))
}
render() { let { results } = this.state; return ( <div className='autocomp_wrapper'> <input placeholder="Enter your search.." onChange={this.handleInput} /> <div> {results.map(item=>{item})} </div> </div> ); }}export default autocomp;let { results } = this.state;
return (
<div className='autocomp_wrapper'>
<input placeholder="Enter your search.." onChange={this.handleInput} />
<div>
{results.map(item=>{item})}
</div>
</div>
);
}
}
export default autocomp;
在我们的 autocomp
组件中,一旦我们在输入框中输入一个单词,它就会请求 api/users
获取要显示的用户列表。 在每个字母输入后,触发异步网络请求,并且成功后通过 this.setState
更新DOM。
现在,想象一下输入 fidudusola
尝试搜索结果 fidudusolanke
,将有许多名称与 fidudusola
一起出现。
1. f2. fi3. fid4. fidu5. fidud6. fidudu7. fidudus8. fiduduso9. fidudusol10. fidudusola
2. fi
3. fid
4. fidu
5. fidud
6. fidudu
7. fidudus
8. fiduduso
9. fidudusol
10. fidudusola
这个名字有 10 个字母,所以我们将有 10 次 API 请求和 10 次 DOM 更新,这只是一个用户而已!! 输入完成后最终看到我们预期的名字 fidudusolanke
和其他结果一起出现。
即使 autocomp
可以在没有网络请求的情况下完成(例如,内存中有一个本地“数据库”),仍然需要为输入的每个字符/单词进行昂贵的 DOM 更新。
const data = [ { name: 'nnamdi' }, { name: 'fidudusola' }, { name: 'fashola' }, { name: 'fidudusolanke' }, // ... up to 10,000 records]
{
name: 'nnamdi'
},
{
name: 'fidudusola'
},
{
name: 'fashola'
},
{
name: 'fidudusolanke'
},
// ... up to 10,000 records
]
class autocomp extends React.Component { constructor(props) { super(props); this.state= { results: [] } }
constructor(props) {
super(props);
this.state= {
results: []
}
}
handleInput = evt => { const value = evt.target.value const filteredRes = data.filter((item)=> { // algorithm to search through the `data` array }) this.setState({ results: filteredRes }) }
const value = evt.target.value
const filteredRes = data.filter((item)=> {
// algorithm to search through the `data` array
})
this.setState({ results: filteredRes })
}
render() { let { results } = this.state; return ( <div className='autocomp_wrapper'> <input placeholder="Enter your search.." onChange={this.handleInput} /> <div> {results.map(result=>{result})} </div> </div> ); }}let { results } = this.state;
return (
<div className='autocomp_wrapper'>
<input placeholder=<