javascript - 如何将 componentDidMount() 和 componentWillUnmount 转换为 useEffect()?
问题描述
我正在尝试创建一个弹出窗口,通知用户在他们离开时按保存进度。我需要将以下代码转换为钩子:
class Prompt extends React.Component {
componentDidMount() {
window.addEventListener('beforeunload', this.beforeunload.bind(this));
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.beforeunload.bind(this));
}
beforeunload(e) {
if (this.props.dataUnsaved) {
e.preventDefault();
e.returnValue = true;
}
}
render() {...}
}
我知道我应该使用 useEffect() 但不确定如何,因为我通常不熟悉钩子。特别是我不确定将什么作为第二个参数,因为钩子不喜欢 this.bind。任何帮助将不胜感激。
解决方案
根据反应文档:
如果熟悉 React 类生命周期方法,可以将 useEffect Hook 视为 componentDidMount、componentDidUpdate 和 componentWillUnmount 的组合。
所以 componentDidMount 将是:
useEffect(() => { // yourCode },[])
并且由于 componentWillUnmout 用于清理请参阅 React Docs,您可以像这样使用它作为回报:
useEffect(() => {
window.addEventListener('beforeunload', () => {});
return () => {
window.removeEventListener('beforeunload', () => {})
}
}, [])
推荐阅读
- python - (已解决)有没有办法退出/结束旧递归(函数())而不完成它们?
- c# - System.InvalidOperationException:无法确定 Class.Property IEnumerable 的导航属性表示的关系
- powershell - 从变量中删除重复条目
- scala - (如何)你能 curry 组成一元函数吗?
- php - 我正在编写一个用于从多个表中选择行的 mysql 查询。我正在使用 mysql IN 运算符,以便我可以从给定的 IDS 集中进行选择
- python - 将参数传递给函数时如何定义条件?(在python中编码更有效)
- javascript - 有没有办法在赛普拉斯中对规范级别的文本进行断言?
- reactjs - 在 REACT 中复制而不引用状态对象
- javascript - Agora Web SDK NG - 存在停止屏幕共享事件?
- reporting-services - 报表生成器聚合函数与 power bi 数据集