javascript - componentWillUpdate 在 React 中被弃用,我该如何替换它?

标签 javascript reactjs

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

React 不推荐使用componentWillMountcomponentWillReceivePropscomponentWillUpdate

在那种情况下,我应该使用什么来代替 componentWillUpdate? 例如,在下面的代码中,我该如何替换 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() 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.

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

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


本答案基于React16.6.3

关于javascript - componentWillUpdate 在 React 中被弃用,我该如何替换它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51644862/

相关文章:

javascript - ( react )在谷歌地图上打开模式标记点击

reactjs - 失败的 Prop 类型 : Invalid prop `children` of type `string` supplied to `DetailField` , 预期 `object`

reactjs - 如何在此 ant design 登录表单中实现最少 5 个字符的验证?我找不到示例

node.js - fs.writeFile 在我的 ReactJs/NodeJs 应用程序上不起作用

ruby-on-rails - 在rails 4应用程序中调用react-modal时出错

javascript - Mousetrap - 添加包装特定元素会出现错误 a.attachEvent 不是函数

javascript - 创建 Web 小部件时,我应该使用容器 div 上的数据属性还是应该向脚本添加参数?

javascript - 禁用警报();

javascript - 谷歌地图标记信息窗口

javascript - 使用 highstock.js 时显示控制台错误的 Highchart 图表同步