问题描述
比方说我有:
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()
?
1楼
Tholle
3
已采纳
2019-02-12 22:18:57
React Component
将始终被重新渲染,但实现了一个带有浅的prop和状态比较的shouldComponentUpdate
,因此除非更改了props,否则它不会重新渲染。
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>