Reactjs 作为道具的反应钩相关功能
在阅读了hooks的介绍之后,我立即感觉到它在传递函数道具方面存在性能问题 考虑下面的类组件,其中函数引用是绑定函数,因此不会因此而发生重新渲染Reactjs 作为道具的反应钩相关功能,reactjs,react-hooks,Reactjs,React Hooks,在阅读了hooks的介绍之后,我立即感觉到它在传递函数道具方面存在性能问题 考虑下面的类组件,其中函数引用是绑定函数,因此不会因此而发生重新渲染 import React from 'react'; class Example extends React.Component { state = { count: 0 } onIncrementClicked = () => setState({ count: this.state.count + 1 }) render()
import React from 'react';
class Example extends React.Component {
state = { count: 0 }
onIncrementClicked = () => setState({ count: this.state.count + 1 })
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={this.onIncrementClicked}>
Click me
</button>
</div>
);
}
}
现在将其与hooks版本进行比较,在hooks版本中,我们在每个渲染上向按钮传递一个新函数。如果组件渲染,则无法避免重新渲染其子组件
我知道这是一个小例子,但是考虑一个更大的应用程序,其中很多回调都依赖于钩子。如何对此进行优化
如何避免重新呈现依赖于钩子的函数属性的所有内容?您可以使用它来确保事件处理程序不会在具有相同计数值的呈现之间更改: 为了更好地优化,您可以将计数值存储为按钮的属性,这样您就不需要访问事件处理程序中的此变量:function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
const handleClick = useCallback(
(e) => setCount(parseInt(e.target.getAttribute('data-count')) + 1),
[]
);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick} data-count={count}>
Click me
</button>
</div>
);
}
另请检查常见问题解答明确提到了这一点,并表示这不应该是个问题:setCountc=>c+1在这种情况下也可以工作,不依赖于计数。
const handleClick = useCallback(
() => {
setCount(count + 1)
},
[count],
);
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
const handleClick = useCallback(
(e) => setCount(parseInt(e.target.getAttribute('data-count')) + 1),
[]
);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={handleClick} data-count={count}>
Click me
</button>
</div>
);
}