在React中不建议使用componentWillUpdate,我该如何替换它? [英] componentWillUpdate is deprecated in React, how can I replace it?

查看:48
本文介绍了在React中不建议使用componentWillUpdate,我该如何替换它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React 16.3.0发布了,React生命周期发生了变化.

React 16.3.0 was released and there were changes in React lifecycles.

React不建议使用 componentWillMount componentWillReceiveProps componentWillUpdate .

React does not recommend to use componentWillMount, componentWillReceiveProps, componentWillUpdate.

在那种情况下,我应该使用什么代替 componentWillUpdate ?例如,在以下代码中,如何替换 componentWillUpdate ?

In that case, what should I use instead of componentWillUpdate? For example, in the following code how can I replace componentWillUpdate?

import React from "react";
import Modal from "./Modal";

class ModalContainer extends React.Component {
  state = {
    openModal: false
  };
  onClick = () => {
    this.setState({
      openModal: !this.state.openModal
    });
  };

  escapeKey = e => {
    if (e.key === "Escape" && this.state.openModal === true) {
      this.setState({
        openModal: !this.state.openModal
      });
    }
  };
  componentDidMount() {
    document.body.classList.add("no-scroll");
    this.componentWillUpdate(this.state, this.state);
  }
  componentWillUpdate(p, c) {
    if (c.openModal) {
      window.addEventListener("keyup", this.escapeKey);
    } else {
      window.removeEventListener("keyup", this.escapeKey);
    }
  }
  componentWillUnmount() {
    window.removeEventListener("keyup", this.escapeKey);
  }

  render(props) {
    return (
      <div className="ModalContainer">
        <a className={`ModalContainer-trigger`} onClick={this.onClick}>
          click here to open the modal
        </a>
        {this.state.openModal && (
          <Modal
            onClick={this.onClick}
            in={!!this.state.openModal}
            {...this.props}
          />
        )}{" "}
      </div>
    );
  }
}
export default ModalContainer;

谢谢

推荐答案

看看 getSnapshotBeforeUpdate

https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate

在最近渲染的输出提交给

getSnapshotBeforeUpdate()之前,例如DOM.它使您的组件可以在DOM可能发生更改之前从DOM中捕获一些信息(例如,滚动位置).

getSnapshotBeforeUpdate() is invoked right before the most recently rendered output is committed to e.g. the DOM. It enables your component to capture some information from the DOM (e.g. scroll position) before it is potentially changed.

顺便说一句,我认为使用这种方法的用例并不多.

Btw, I think there's not much use case to use such method.

如果要在任何状态更改后产生副作用,仍可以使用 componentDidUpdate .

You can still use componentDidUpdate if you want to have side effects after any states changed.

此答案基于React16.6.3

This answer based on React16.6.3

这篇关于在React中不建议使用componentWillUpdate,我该如何替换它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆