我正在将使用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]);
慕莱坞森
相关分类