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;
谢谢