pan*_*ang 7 html javascript css reactjs
所以我目前正在使用 React Hooks,我正在尝试使用 useEffect。它假设每当依赖关系发生变化时,useEffect 就会重新渲染,对吗?但这对我不起作用。这是我的代码:
const [slidesPerView, setSlidesPerView] = React.useState(0)
React.useEffect(() => {
setSlidesPerView(() => (window.innerWidth <= 375 ? 1 : 2))
console.log("rerender?", slidesPerView)
}, [window.innerWidth])
Run Code Online (Sandbox Code Playgroud)
每次更改屏幕尺寸时,useEffect 都不会重新渲染。我想知道我做错了什么?
rav*_*l91 11
useEffect将响应props变化或state变化。
每次屏幕大小更改组件都不知道是否window.innerWidth更改,因为它不在 astate或props.
为了让它工作,你需要存储window.innerWidth到 state 中,并将一个事件监听器附加到你的window,每当window大小改变时,它都会获取window.innerWidth并将其存储到 中state,并且随着state更改,你useEffect将重新运行,最后你的组件将重新运行使成为。
const [size, setSize] = React.useState(window.innerWidth)
React.useEffect(() => {
//Attach event on window which will track window size changes and store the width in state
window.addEventListener("resize", updateWidth);
setSlidesPerView(() => (size <= 375 ? 1 : 2));
console.log("rerender?", slidesPerView);
//It is important to remove EventListener attached on window.
return () => window.removeEventListener("resize", updateWidth);
}, [size])
const updateWidth = () => {
setSize(window.innerWidth)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4347 次 |
| 最近记录: |