假设我有:
class Item extends React.Component {
render() {
console.log('Let's assume this does something slow...');
return <li>{this.props.text}</li>;
}
}
class List extends React.Component {
constructor() {
super();
this.state = {
items: [],
};
}
addItem = text => {
this.setState({
// Mutates the array reference... is there a way around it?
items: this.state.items.concat({ id: Math.random(), text }),
});
};
render() {
return (
<div>
<button onClick={() => this.addItem(Math.random())}>Add Item</button>
<ul>
// This will run on every render, re-rendering the whole list...
{this.state.items.map(item => (
<Item key={item.id} text={item.text} />
))}
</ul>
</div>
);
}
}
是否可以完全保留现有列表,而我只需在顶部/底部添加一个新项目,而无需调用其同级的render()
?
答案 0 :(得分:3)
React Component
将始终被重新渲染,但是PureComponent
实现的shouldComponentUpdate
具有较浅的属性和状态比较,因此除非这些属性是改变了。
class Item extends React.PureComponent {
render() {
console.log("Let's assume this does something slow...");
return <li>{this.props.text}</li>;
}
}
class List extends React.Component {
state = {
items: []
};
addItem = text => {
this.setState(prevState => {
return { items: [...prevState.items, { id: Math.random(), text }] };
});
};
render() {
return (
<div>
<button onClick={() => this.addItem(Math.random())}>Add Item</button>
<ul>
{this.state.items.map(item => (
<Item key={item.id} text={item.text} />
))}
</ul>
</div>
);
}
}
ReactDOM.render(<List />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>