【发布时间】:2020-02-21 07:03:42
【问题描述】:
我正在将使用 componentDidMount/Update/Unmount 生命周期的代码转换为 React Hooks,并在控制台中不断遇到 react-hooks/exhaustive-deps 作为警告。
我们的新代码似乎按预期工作,因此我的想法是关闭这些警告。但是,如果我遗漏了什么,下面的代码中是否需要警告。
旧componentDidMount/Update/Unmount代码
state = {
container: canUseDOM ? createContainer(this.props.zIndex) : undefined,
portalIsMounted: false,
};
componentDidUpdate(prevProps: Props, prevState: State) {
const { container } = this.state;
const { zIndex } = this.props;
if (container && prevProps.zIndex !== zIndex) {
const newContainer = createContainer(zIndex);
getPortalParent().replaceChild(container, newContainer);
this.setState({ container: newContainer });
} else if (!prevState.container && container) {
getPortalParent().appendChild(container);
}
}
componentDidMount() {
const { container } = this.state;
const { zIndex } = this.props;
if (container) {
getPortalParent().appendChild(container);
} else {
const newContainer = createContainer(zIndex);
this.setState({ container: newContainer });
}
this.setState({
portalIsMounted: true,
});
firePortalEvent(PORTAL_MOUNT_EVENT, Number(zIndex));
}
componentWillUnmount() {
const { container } = this.state;
const { zIndex } = this.props;
if (container) {
getPortalParent().removeChild(container);
const portals = !!document.querySelector(
'body > .portal-container > .portal',
);
if (!portals) {
getBody().removeChild(getPortalParent());
}
}
firePortalEvent(PORTAL_UNMOUNT_EVENT, Number(zIndex));
}
新的 React Hooks 代码
const [container, setContainer] = useState(canUseDOM ? createContainer(zIndex) : undefined);
const [portalIsMounted, setPortalIsMounted] = useState(false);
useEffect(() => {
if (container) {
const newContainer = createContainer(zIndex);
getPortalParent().replaceWith(container, newContainer);
setContainer(newContainer);
}
}, [zIndex]);
useEffect(() => {
if (container) {
getPortalParent().appendChild(container);
}
}, [container]);
useEffect(() => {
if (container) {
getPortalParent().appendChild(container);
} else {
const newContainer = createContainer(zIndex);
setContainer(newContainer);
}
setPortalIsMounted(true);
firePortalEvent(PORTAL_MOUNT_EVENT, Number(zIndex));
}, []);
useEffect(() => {
if (container) {
getPortalParent().removeChild(container);
const portals = !!document.querySelector(
'body > .portal-container > .portal'
);
if (!portals) {
getBody().removeChild(getPortalParent());
}
}
firePortalEvent(PORTAL_UNMOUNT_EVENT, Number(zIndex));
}, []);
【问题讨论】:
-
componentWillUnmount的代码应该从useEffect回调返回
标签: javascript reactjs react-hooks