Reactjs 如何在渲染后更新状态
我有以下组成部分:Reactjs 如何在渲染后更新状态,reactjs,Reactjs,我有以下组成部分: 从“React”导入React; 导入“./styles.css”; 从“../../Common/components/ToolTip/ToolTip”导入工具提示; 导出默认类RouteTitleToolIPComponent扩展React.Component{ 建造师(道具){ 超级(道具); this.titleParagraphhref=React.createRef(); 这是。_tooltipTimer=null; this.state={shouldPopup
从“React”导入React;
导入“./styles.css”;
从“../../Common/components/ToolTip/ToolTip”导入工具提示;
导出默认类RouteTitleToolIPComponent扩展React.Component{
建造师(道具){
超级(道具);
this.titleParagraphhref=React.createRef();
这是。_tooltipTimer=null;
this.state={shouldPopupBeEnabled:false,istoltipshown:false};
this.\u showTooltip=this.\u showTooltip.bind(this);
this.\u hideTooltip=this.\u hideTooltip.bind(this);
}
componentDidMount(){
const{scrollWidth,clientWidth}=this.titleParagraphhref.current;
const shouldPopupBeEnabled=scrollWidth>clientWidth;
this.setState({shouldPopupBeEnabled});
}
_showTooltip(){
这是。_tooltipTimer=setTimeout(
() => {
this.setState({isTooltipShown:true});
}, 1000,
);
}
_hideTooltip(){
clearTimeout(此.\u ToolTimper);
this.setState({isTooltipShown:false});
}
render(){
const{shouldPopupBeEnabled,istoltipshown}=this.state;
const{message}=this.props;
返回(
{message}
);
}
}
如果div元素中的消息大于容器,则基本上会在div元素上呈现浮动工具提示。为此,我使用refact引用使用div元素的scrollWidth
和clientWidth
。为了检测这些值,我使用了componentDidMount
,但这只适用于组件的完整呈现。也就是说,如果我让组件可见并重新加载页面,则两个值都等于0,并且不起作用
此外,如果我更改消息,它也不会工作,因为组件已经装入
因此,我想要的是在安装或更新组件之后立即更改状态,以便呈现react引用,并且clientWidth
和scrollWidth
不是0
我尝试过替换componentdiddupdate
而不是componentDidMount
,但是在componentdiddupdate
内部使用setState
不是一个好的做法
有解决方案吗?首先,您应该知道
componentDidMount
只执行一次。因此,您可以选择componentdiddupdate
,但不要忘记设置一个条件,因为它将在循环中呈现
componentDidUpdate(prevProps,prevState) {
const shouldPopupBeEnabled = scrollWidth > clientWidth;
if (shouldPopupBeEnabled !== this.state.shouldPopupBeEnabled ) {
this.setState({shouldPopupBeEnabled });
}
}
或者,您可以选择功能组件并使用useEffect,它只会在状态更改时再次渲染
useEffect(() => {
console.log('mounted');
}, [shouldPopupBeEnabled]) // It will re render id `shouldPopupBeEnabled` changes
在我看来,最好切换到功能组件并使用useLayoutEffect。什么是
useLayoutEffect
?它可以帮助您在更新状态后立即进行DOM变异。哦,它已经成功了。你能把它作为答案贴出来吗?