如何避免在渲染方法中使用此绑定方式,或者说有什么替代方法?
如果您关心重新渲染,则shouldComponentUpdate和PureComponent是您的好朋友,它们将帮助您优化渲染。
您需要从“父”组件中提取“子”组件,并始终传递相同的props并实现shouldComponentUpdate或使用PureComponent。我们想要的情况是,当我们删除一个子组件时,其他子组件不应该被重新渲染。
示例:
import React, { Component, PureComponent } from 'react';
import { render } from 'react-dom';
class Product extends PureComponent {
render() {
const { id, name, onDelete } = this.props;
console.log(`<Product id=${id} /> render()`);
return (
<li>
{id} - {name}
<button onClick={() => onDelete(id)}>Delete</button>
</li>
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = {
products: [
{ id: 1, name: 'Foo' },
{ id: 2, name: 'Bar' },
],
};
this.handleDelete = this.handleDelete.bind(this);
}
handleDelete(productId) {
this.setState(prevState => ({
products: prevState.products.filter(product => product.id !== productId),
}));
}
render() {
console.log(`<App /> render()`);
return (
<div>
<h1>Products</h1>
<ul>
{
this.state.products.map(product => (
<Product
key={product.id}
onDelete={this.handleDelete}
{...product}
/>
))
}
</ul>
</div>
);
}
}
render(<App />, document.getElementById('root'));
演示:https://codesandbox.io/s/99nZGlyZ
预期行为
<App />
渲染()
<Product id=1...>
渲染()
<Product id=2...>
渲染()
当我们移除<Product id=2 ...
时,只有<App />
被重新渲染。
要在演示中看到这些消息,请打开开发者工具控制台。
相同的技术已经被用于并且描述在文章中:React is Slow, React is Fast: Optimizing React Apps in Practice by François Zaninotto.