2019-12-16

一、你知道初始化state的正确姿势吗?

相信有很多码友在初始化state的时候会使用以下的方式:

class ExampleComponent extends React.Component {
  state = {};

  componentWillMount() {
    this.setState({
      currentColor: this.props.defaultColor,
      palette: 'rgb',
    });
  }
}

这可就麻烦了,因为componentWillMount只会在加载阶段执行一次,虽然setState会引发render,但是这个时候还没有第一次render所以setState后我们的界面仍不会有改变。故而我们不应该在componentWillMount里进行state的初始化,正确的姿势请看下方代码

class ExampleComponent extends React.Component {
  state = {
    currentColor: this.props.defaultColor,
    palette: 'rgb',
  };
}

class ExampleComponent extends React.Component {
constructor(props){
    super(props)
    this.state={
    currentColor: props.defaultColor,
    palette: 'rgb',
        }
    }

这两种方式都可以,没有优劣之分,但是如果你需要在constructor里面去绑定事件函数,就需要使用第二种啦

二、获取外部数据需要注意哦

我们搞一个页面,免不了的就是去获取外部数据,那究竟我们应该在何时何地获取它最为合理恰当呢?相信这也是多数才接触react的码友的困恼之处。我们先来看看容易犯错的地方,即在componentWillMonut里面去获取外部数据

class ExampleComponent extends React.Component {
  state = {
    externalData: null,
  };

  componentWillMount() {
    this._asyncRequest = loadMyAsyncData().then(
      externalData => {
        this._asyncRequest = null;
        this.setState({externalData});
      }
    );
  }

  componentWillUnmount() {
    if (this._asyncRequest) {
      this._asyncRequest.cancel();
    }
  }

  render() {
    if (this.state.externalData === null) {
      // Render loading state ...
    } else {
      // Render real UI ...
    }
  }
}

大家都知道,componentWillMonut是在render之前被调用,也就是说这时候是还没有渲染出dom结构的,及时获取到数据也没有办法渲染到页面中,而且在之后即将到来的react17将采用异步渲染,componentWillMonuti将可能会被调用多次,如果在里面进行获取数据这些异步操作,会导致多次请求,所以正确的姿势如下

class ExampleComponent extends React.Component {
  state = {
    externalData: null,
  };

  componentDidMount() {
    this._asyncRequest = loadMyAsyncData().then(
      externalData => {
        this._asyncRequest = null;
        this.setState({externalData});
      }
    );
  }

  componentWillUnmount() {
    if (this._asyncRequest) {
      this._asyncRequest.cancel();
    }
  }

  render() {
    if (this.state.externalData === null) {
      // Render loading state ...
    } else {
      // Render real UI ...
    }
  }
}

我们应该在componentDidMount里面进行获取外部数据操作,这时组件已经完全挂载到网页上,所以可以保证数据的加载。此外,在这方法中调用setState方法,会触发重渲染。所以,官方设计这个方法就是用来加载外部数据用的,或处理其他的副作用代码。
还有就是,我们如果需要进行订阅,也不要在componentWillMount里面进行订阅,应该在componentDidMount里面进行订阅,在componentWillUnmount里面取消订阅

三、根据props更新state

往往在比较复杂的页面中,我们免不了通过props传递属性给子组件,子组件通过props来更新自身的state,且看以往我们的做法:

class ExampleComponent extends React.Component {
  state = {
    isScrollingDown: false,
  };

  componentWillReceiveProps(nextProps) {
    if (this.props.currentRow !== nextProps.currentRow) {
      this.setState({
        isScrollingDown:
          nextProps.currentRow > this.props.currentRow,
      });
    }
  }
}

我们常常会在componentWillReceiveProps这个生命周期里去比较新旧props来更新state,但随着新的生命周期getDerivedStateFromProps的出现,我们就不应该再使用这种方式了,而应该使用getDerivedStateFromProps:

class ExampleComponent extends React.Component {
  // Initialize state in constructor,
  // Or with a property initializer.
  state = {
    isScrollingDown: false,
    lastRow: null,
  };

  static getDerivedStateFromProps(props, state) {
    if (props.currentRow !== state.lastRow) {
      return {
        isScrollingDown: props.currentRow > state.lastRow,
        lastRow: props.currentRow,
      };
    }

    // Return null to indicate no change to state.
    return null;
  }
}

您可能会注意到,在上面的示例中,该props.currentRow状态已镜像(如state.lastRow)。这样就可以getDerivedStateFromProps按照中的相同方式访问先前的props值componentWillReceiveProps。下面是官方给出的未提供prevProps的理由:

您可能想知道为什么我们不只是将先前的prop作为参数传递给getDerivedStateFromProps。我们在设计API时考虑了此选项,但最终出于以下两个原因而决定:

prevProps首次getDerivedStateFromProps调用(实例化之后)的参数为null
,要求在每次prevProps访问时都添加if-not-null检查。
不将先前的props传递给此功能是朝着将来的React版本释放内存的一步。(如果React不需要将先前的prop传递到生命周期,那么它就不需要将先前的props对象保留在内存中。)

四、props改变产生的副作用

有时候,当props改变时,我们会进行一些除更新state之外的操作,比如调用外部方法,获取数据等,以前我们可能一股脑的将这些操作放在componentWillReceiveProps中,像下面这样:

// Before
class ExampleComponent extends React.Component {
  componentWillReceiveProps(nextProps) {
    if (this.props.isVisible !== nextProps.isVisible) {
      logVisibleChange(nextProps.isVisible);
    }
  }
}

但这是不可取的,因为一次更新可能会调用多次componentWillReceiveProps,因此,重要的是避免在此方法中产生副作用。相反,componentDidUpdate应该使用它,因为它保证每次更新仅被调用一次:

class ExampleComponent extends React.Component {
  state = {
    externalData: null,
  };

  static getDerivedStateFromProps(props, state) {
    // Store prevId in state so we can compare when props change.
    // Clear out previously-loaded data (so we don't render stale stuff).
    if (props.id !== state.prevId) {
      return {
        externalData: null,
        prevId: props.id,
      };
    }

    // No state update necessary
    return null;
  }

  componentDidMount() {
    this._loadAsyncData(this.props.id);
  }

  componentDidUpdate(prevProps, prevState) {
    if (this.state.externalData === null) {
      this._loadAsyncData(this.props.id);
    }
  }

  componentWillUnmount() {
    if (this._asyncRequest) {
      this._asyncRequest.cancel();
    }
  }

  render() {
    if (this.state.externalData === null) {
      // Render loading state ...
    } else {
      // Render real UI ...
    }
  }

  _loadAsyncData(id) {
    this._asyncRequest = loadMyAsyncData(id).then(
      externalData => {
        this._asyncRequest = null;
        this.setState({externalData});
      }
    );
  }
}

像上面的代码一样,我们应该将状态更新与获取外部数据分离开来,将数据更新移至componentDidUpdate。

五、如何优雅的获取更新前的dom属性

我们常常会有这样的需求,就是在组件更新后我要保留一些更新前的属性,这就需要在更新前做相关的保存操作。在新的生命周期getSnapshotBeforeUpdate还没有出来之前,我们实现这一需求的方式就只有在componentWillUpdate去手动保存我们需要的属性,在componentDidUpdate里去使用:

class ScrollingList extends React.Component {
  listRef = null;
  previousScrollOffset = null;

  componentWillUpdate(nextProps, nextState) {
    // Are we adding new items to the list?
    // Capture the scroll position so we can adjust scroll later.
    if (this.props.list.length < nextProps.list.length) {
      this.previousScrollOffset =
        this.listRef.scrollHeight - this.listRef.scrollTop;
    }
  }

  componentDidUpdate(prevProps, prevState) {
    // If previousScrollOffset is set, we've just added new items.
    // Adjust scroll so these new items don't push the old ones out of view.
    if (this.previousScrollOffset !== null) {
      this.listRef.scrollTop =
        this.listRef.scrollHeight -
        this.previousScrollOffset;
      this.previousScrollOffset = null;
    }
  }

  render() {
    return (
      <div ref={this.setListRef}>
        {/* ...contents... */}
      </div>
    );
  }

  setListRef = ref => {
    this.listRef = ref;
  };
}

但是这样会有许多弊端,使用异步渲染时,“渲染”阶段生命周期(如componentWillUpdate和render)和“提交”阶段生命周期(如componentDidUpdate)之间可能会有延迟。如果用户在此期间进行了诸如调整窗口大小的操作,则scrollHeight从中读取的值componentWillUpdate将过时。

解决此问题的方法是使用新的“提交”阶段生命周期getSnapshotBeforeUpdate。在进行突变之前(例如在更新DOM之前)立即调用此方法。它可以返回一个值,以使React作为参数传递给componentDidUpdate,在发生突变后立即被调用。如下:

class ScrollingList extends React.Component {
  listRef = null;

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // Are we adding new items to the list?
    // Capture the scroll position so we can adjust scroll later.
    if (prevProps.list.length < this.props.list.length) {
      return (
        this.listRef.scrollHeight - this.listRef.scrollTop
      );
    }
    return null;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // If we have a snapshot value, we've just added new items.
    // Adjust scroll so these new items don't push the old ones out of view.
    // (snapshot here is the value returned from getSnapshotBeforeUpdate)
    if (snapshot !== null) {
      this.listRef.scrollTop =
        this.listRef.scrollHeight - snapshot;
    }
  }

  render() {
    return (
      <div ref={this.setListRef}>
        {/* ...contents... */}
      </div>
    );
  }

  setListRef = ref => {
    this.listRef = ref;
  };
}

这两个生命周期一定是成双成对出现的,不然会报错,而且在getSnapshotBeforeUpdate中的返回值会直接作为componentDidUpdate的参数传递进去,并不需要我们去手动保存状态。十分的方便。

以上就是我对react的生命周期的用法的一些总结,如有不对之处,还望各位读者不吝赐教,谢谢大家。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,402评论 6 499
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,377评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,483评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,165评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,176评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,146评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,032评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,896评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,311评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,536评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,696评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,413评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,008评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,815评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,698评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,592评论 2 353

推荐阅读更多精彩内容