images.jpeg
原文永久链接: https://github.com/Attemptweb.....
下面说到的 React 开发中注意的问题, 部分是自己遇到过的点, 部分是收集的, 也算是 React 代码优化部分, 这次做一个整理, 希望可以帮助到你
- shouldComponentUpdate
- React.PureComponent
3. 不可变 Immutable
4.React 的 key 标识
5. 虚拟化长列表
6.React.memo 函数组件
7. 不滥用 props 和 state
8. 拆分组件
避免重复渲染
当组件的 props 或者 state 改变时, 可能会出现重复 setState 的情况, 对于重复的操作, 我们可以通过下面的方法来避免重复渲染:
shouldComponentUpdate
shouldComponentUpdate 返回 true, 确认真实 DOM 需要改变时, 返回 true. 一般的做法是比较组件的 props 和 state 是否真的发生变化, 如果发生变化则返回 true, 否则返回 false.
- shouldComponentUpdate(nextProps, nextState) {
- if (this.props.id !== nextProps.id) {
- return true;
- }
- if (this.state.type !== nextState.type) {
- return true;
- }
- return false;
- }
React 文档: shouldComponentUpdate()
React 文档: shouldComponentUpdate 的作用
React.PureComponent
React.PureComponent, 不必写你自己的 shouldComponentUpdate, 它提供了一个浅比较. 如果对象中包含复杂的数据结构, 则有可能因为无法检查深层的差别, 产生错误的比对结果. 在你的 props 和 state 较为简单时, 可以使用 React.PureComponent.(补充: 当你比较的目标为引用类型数据, 浅比较会忽略属性或状态)
- class ChildComponent extends React.PureComponent {
- render() {
- return(
- <>{this.state.type}</>
- )
- }
- }
React 文档: React.PureComponent
不可变 Immutable
不可变 Immutable,Immutable Data 就是一旦创建, 就不能再被更改的数据. 对 Immutable 对象的任何修改或添加删除操作都会返回一个新的 Immutable 对象. 更多详情: Immutable 详解及 React 中实践
- import { Map, is } from 'immutable';
- constructor() {
- this.state = {
- // 创建 不可变 Immutable
- data: Map({ times: 0 })
- }
- }
- shouldComponentUpdate(nextProps, nextState) {
- for (const key in nextState) {
- // 通过 is 或者 !== 来比对
- if (this.state[key] !== nextState[key] && !is(this.state[key], nextState[key])) {
- return true;
- }
- }
- }
- handleAdd() {
- // 一个全新的对象
- const newData = this.state.data.update('times', v => v + 1);
- this.setState({ data: newData);
- }
- listData.map((item) =>
- <li key={item.id}>
- {item.text}
- </li>
- );
- react-virtualized
- react-Windows
- function areEqual(prevProps, nextProps) {
- /*
- 如果把 nextProps 传入 render 方法的返回结果与
- 将 prevProps 传入 render 方法的返回结果一致则返回 true,
- 否则返回 false
- */
- }
- function Component(props) {
- }
- React.memo(Component, areEqual)
来源: http://www.jianshu.com/p/16e7509dd957