React 16.3.0 发布,React 生命周期发生了变化。
React 不推荐使用componentWillMount
、componentWillReceiveProps
、componentWillUpdate
。
在那种情况下,我应该使用什么来代替 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/