五大react生命周期使用注意事项,绝对干货

五大react使用注意事项

一、你知道初始化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的生命周期的用法的一些总结,如有不对之处,还望各位读者不吝赐教,谢谢大家。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北街学长

你的鼓励使我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值