gpt4 book ai didi

javascript - react : Pass function property down to pure child component - Rerendering

转载 作者:行者123 更新时间:2023-12-03 14:16:56 25 4
gpt4 key购买 nike

我是 React 新手。我正在阅读有关纯组件的内容(“Pure React”是我正在阅读的那本书),并且遇到了这个让我感到困惑的示例。书上说:

It’s generally a bad idea to create newly define functions to pass into props like the code below. It's bad because passing a new function down to a pure component every time it renders means that it will always see “new” props, and therefore always re-render (needlessly). Avoid creating a new function in render when (a) the child component receiving the function prop is pure and (b) you expect the parent component to re-render often.

class App extends Component {
// ...
renderContent() {
switch(this.state.activeTab) {
default:
case 0: return <span>Items</span>;
case 1: return <span>Cart</span>;
}
}

render() {
let {activeTab} = this.state;
return (
<div className="App">
<Nav activeTab={activeTab} onTabChange={this.handleTabChange} />
<main className="App-content">
{this.renderContent()}
</main>
</div>
);
}
}

const Nav = ({ activeTab, onTabChange }) => (
<nav className="App-nav">
<ul>
<li className={`App-nav-item ${activeTab === 0 && 'selected'}`}>
<a onClick={() => onTabChange(0)}>Items</a>
</li>
<li className={`App-nav-item ${activeTab === 1 && 'selected'}`}>
<a onClick={() => onTabChange(1)}>Cart</a>
</li>
</ul>
</nav>
);

我很困惑,因为我们没有将新定义的函数传递给另一个 React 组件。我们正在“a”元素的 onClick 属性上定义一个新函数。那么,对于上面的代码,我们是否会进行不需要的额外重新渲染?它不会不必要地重新渲染,因为我没有将“() => onTabChange(1)”作为 prop 传递给 React 纯子组件,对吧?

这本书的作者是否试图让我们想象有一个纯 React 组件来代替上面代码中的“a”元素?

最佳答案

您没有在导航组件上传递新的箭头函数,并且它不会重新渲染,因为您在 a 元素上使用箭头函数,即使在元素上使用新函数也是一种不好的做法,并不是因为这个原因导航渲染是针对每次在组件上提供 props 时的 React 行为,它会自动渲染,以防止您可以在此处使用纯组件作为类组件,使用备忘录作为功能组件和示例,以避免使用备忘录重新渲染:

const NavMemo = React.memo(({ activeTab, onTabChange }) => {
console.log('Render');
return (
<nav className="App-nav">
<ul>
<li className={`App-nav-item ${activeTab === 0 && 'selected'}`}>
<a onClick={() => onTabChange(0)}>Items</a>
</li>
<li className={`App-nav-item ${activeTab === 1 && 'selected'}`}>
<a onClick={() => onTabChange(1)}>Cart</a>
</li>
</ul>
</nav>
);
});

React 文档是: https://reactjs.org/docs/react-api.html#reactmemo

关于javascript - react : Pass function property down to pure child component - Rerendering,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58384377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com