Alf*_*x92 5 javascript reactjs
React 16.3.0已发布,并且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;
Run Code Online (Sandbox Code Playgroud)
谢谢
看一眼 getSnapshotBeforeUpdate
https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate
getSnapshotBeforeUpdate() 在最近渲染的输出提交到例如 DOM 之前被调用。它使您的组件能够在可能更改之前从 DOM 中捕获一些信息(例如滚动位置)。
顺便说一句,我认为使用这种方法的用例并不多。
componentDidUpdate如果您想在任何状态更改后产生副作用,您仍然可以使用。
这个答案基于 React16.6.3