[英]React Hook "useState" cannot be called inside a callback. Using useMediaQuery responsive JS media query
I'm trying to use responsive javascript media queries using useMediaQuery
however I can't get it to work, I get: -我正在尝试使用
useMediaQuery
使用响应式 javascript 媒体查询,但是我无法让它工作,我得到:-
Error message: "useState" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
错误消息:
"useState" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
"useState" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function
Playgroundhttps://stackblitz.com/edit/react-ts-5vseqr?file=media-query.ts游乐场https://stackblitz.com/edit/react-ts-5vseqr?file=media-query.ts
I think it's erroring on line 4 of media-query.ts
我认为它在
media-query.ts
第 4 行media-query.ts
import { useState, useEffect } from 'react'
const useMediaQuery = (query: string) => {
const [match, setMatch] = useState(false)
useEffect(() => {
const updateMatch = () => setMatch(window.matchMedia(query).matches)
updateMatch()
window.matchMedia(query).addEventListener('change', updateMatch)
return () => {
window.matchMedia(query).removeEventListener('change', updateMatch)
}
}, [query])
return match
}
export default useMediaQuery
What you've done here is writing a custom hook(useMediaQuery).你在这里所做的是编写一个自定义钩子(useMediaQuery)。 You've done that properly so no issues there.
你做得很好,所以没有问题。 Above code snipped is fine.
上面的代码剪下来很好。
The problem is in the index.tsx file when you try to use the above custom hook that you've written.当您尝试使用您编写的上述自定义挂钩时,问题出在 index.tsx 文件中。 As the error suggests your custom hook is called outside the react component there in line 7 of index.tsx.
由于错误表明您的自定义钩子在 index.tsx 的第 7 行中的 react 组件之外被调用。
You have to move the useMediaQuery call inside the App component.您必须在 App 组件内移动 useMediaQuery 调用。 Also currently your App component is a class component which you have to convert to a functional component to use hooks inside it.
此外,目前您的 App 组件是一个类组件,您必须将其转换为功能组件才能在其中使用钩子。
here's the adjusted code: https://stackblitz.com/edit/react-ts-m6rwpd?file=index.tsx这是调整后的代码: https : //stackblitz.com/edit/react-ts-m6rwpd?file=index.tsx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.