Reactjs 转换';调整大小';eventListener从类到功能组件?
我正在尝试学习React钩子,所以我编写了一个小函数,实时显示窗口的宽度: 类组件:Reactjs 转换';调整大小';eventListener从类到功能组件?,reactjs,react-hooks,Reactjs,React Hooks,我正在尝试学习React钩子,所以我编写了一个小函数,实时显示窗口的宽度: 类组件: state = { windowWidth: window.innerWidth } handleResize = () => this.setState({ windowWidth: window.innerWidth }); handleEvent = () => window.addEventListener("resize", this.handleResize);
state = { windowWidth: window.innerWidth }
handleResize = () => this.setState({ windowWidth: window.innerWidth });
handleEvent = () => window.addEventListener("resize", this.handleResize);
componentDidMount = () => this.handleEvent();
componentWillUnmount = () => this.handleEvent();
/* using { this.state.windowWidth } */
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
const handleResize = () => setWindowWidth(window.innerWidth);
useEffect(() => {
window.addEventListener("resize", handleResize);
}, []);
/* using { windowWidth } */
我试图将其转换为带有React挂钩的功能组件,但对我来说不起作用。怎么了
功能组件:
state = { windowWidth: window.innerWidth }
handleResize = () => this.setState({ windowWidth: window.innerWidth });
handleEvent = () => window.addEventListener("resize", this.handleResize);
componentDidMount = () => this.handleEvent();
componentWillUnmount = () => this.handleEvent();
/* using { this.state.windowWidth } */
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
const handleResize = () => setWindowWidth(window.innerWidth);
useEffect(() => {
window.addEventListener("resize", handleResize);
}, []);
/* using { windowWidth } */
试试这个。
我一直在用它。请记住在卸载后清理eventListener。您必须在useEffect中返回.off
import $ from 'jquery'
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
function handleResize() {
try {
setWindowWidth(window.innerWidth);
} catch (err) {
console.error(err);
}
}
useEffect(() => {
$(window).on('resize', handleResize);
return () => {
$(window).off('resize', handleResize);
};
}, []);
试试这个。
我一直在用它。请记住在卸载后清理eventListener。您必须在useEffect中返回.off
import $ from 'jquery'
const [windowWidth, setWindowWidth] = useState(window.innerWidth);
function handleResize() {
try {
setWindowWidth(window.innerWidth);
} catch (err) {
console.error(err);
}
}
useEffect(() => {
$(window).on('resize', handleResize);
return () => {
$(window).off('resize', handleResize);
};
}, []);
如果在另一个依赖项为windowWidth的useEffect块中添加console.log,会发生什么情况?您是否看到它在控制台中更新了?您能否确切地告诉我们发生了什么以及当前代码中存在什么问题?我在代码沙盒中试用过,效果很好。如果在另一个依赖项为windowWidth的useEffect块中添加console.log,会发生什么情况?您是否看到它在控制台中更新了?您能否确切地告诉我们发生了什么以及当前代码中存在什么问题?我在代码沙盒中试用过,效果很好。