请考虑以下React代码:
class Todos extends React.Component {
constructor(props) {
super(props);
this.state = { item: 'Test', };
}
render() {
return <TodoItem item={this.state.item} />
}
}
class TodoItem extends React.PureComponent {
render() {
return <div>{this.props.item}</div>
}
}
function TodoItem(props) {
return <div>{props.item}</div>
}
上面是有状态父组件 Todos
和同一子组件 TodoItem
的2个版本 . 其中一个版本是纯组件,另一个版本是无状态功能组件 .
我理解使用PureComponent带来的性能优势,但我想知道React 16是否对无状态功能组件应用了相同的浅层比较和性能优势?
如果不是那么为什么?似乎通过使用我告诉React我的组件没有状态,因此只有在父组件的状态发生变化时才会更新 .
2 回答
还没有 . React团队有迹象表明这将在未来发生变化,但截至今天,无状态功能组件在重新渲染方面仍然表现得像React.Component .
如果您需要优化性能,请坚持
React.PureComponent
或React.Component
实施shouldComponentUpdate
. 请记住,如果您正在使用redux和react-redux,connect()
将尝试在功能和基于类的组件(read up on in in the docs)上处理浅层比较 . 例如,您可能还想查看recompose and its onlyUpdateForKeys帮助程序 .这实际上取决于你如何在JSX中调用纯组件 . 使用安装时(如在您的代码段中),它不会为您提供大量优化 . @Dominik和人们在评论的问题中描述了原因 . 但here家伙称,将纯组件称为功能可以使速度提高45% .
Todos
组件将如下所示: