[英]useMediaQuery typescript error (condition will always return true since the function is always defined)
I'm trying to use useMediaQuery
in my react app for my responsive js media queries.我正在尝试在我的响应应用程序中使用
useMediaQuery
来进行响应式 js 媒体查询。 I'm using typescript version 4.0.3.我正在使用打字稿版本 4.0.3。
The code is as follows:代码如下:
import { useState, useEffect } from 'react'
const useMediaQuery = (query: string) => {
const [match, setMatch] = useState(false)
useEffect(() => {
const updateMatch = () => setMatch(window.matchMedia(query).matches)
updateMatch()
if (window.matchMedia(query).addEventListener) {
window.matchMedia(query).addEventListener('change', updateMatch)
} else {
window.matchMedia(query).addListener(updateMatch)
}
return () => {
if (window.matchMedia(query).removeEventListener) {
window.matchMedia(query).removeEventListener('change', updateMatch)
} else {
window.matchMedia(query).removeListener(updateMatch)
}
}
}, [query])
return match
}
export default useMediaQuery
The error message I'm getting is:我收到的错误消息是:
This condition will always return true since the function is always defined. Did you mean to call it instead? TS2774
updateMatch()
if (window.matchMedia(query).addEventListener) {
^
Does anyone have any ideas on how to fix this code to get it working?有没有人对如何修复此代码以使其正常工作有任何想法?
Thanks谢谢
Maybe you just don`t need this condition.也许你只是不需要这个条件。 On my env I have error
在我的环境中我有错误
deprecated MediaQueryList.removeListener
so you will have another issue when fix current所以在修复电流时你会遇到另一个问题
if(window.matchMedia(query).addEventListener) {...}
This will always return the function reference.这将始终返回函数引用。 So it will always execute the if block.
所以它会一直执行 if 块。 That's why typescript is throwing error.
这就是打字稿抛出错误的原因。 So instead of using if/else, you could directly call the methods.
因此,您可以直接调用这些方法,而不是使用 if/else。
window.matchMedia(query).addEventListener('change', updateMatch)
window.matchMedia(query).addListener(updateMatch)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.