Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/466.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 以状态作为条件设置使用中的状态_Javascript_Reactjs_React Hooks - Fatal编程技术网

Javascript 以状态作为条件设置使用中的状态

Javascript 以状态作为条件设置使用中的状态,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,我想在路径名更改后隐藏移动菜单(使用ReactRouter) 下面的代码向我显示了一条警告,因为我没有将mobileOpen作为依赖项跟踪。但它是有效的 const Navbar: React.FC<Props> = props => { const { pathname } = useLocation() const [mobileOpen, setMobileOpen] = useState(false) useEffect(() => { if

我想在路径名更改后隐藏移动菜单(使用ReactRouter)

下面的代码向我显示了一条警告,因为我没有将
mobileOpen
作为依赖项跟踪。但它是有效的

const Navbar: React.FC<Props> = props => {
  const { pathname } = useLocation()
  const [mobileOpen, setMobileOpen] = useState(false)

  useEffect(() => {
    if (mobileOpen) setMobileOpen(false)
    main.current?.scrollTo(0, 0)
  }, [pathname, main])

...
const导航栏:React.FC=props=>{
const{pathname}=useLocation()
常量[mobileOpen,setMobileOpen]=使用状态(false)
useffect(()=>{
如果(mobileOpen)设置mobileOpen(false)
main.current?滚动到(0,0)
},[pathname,main])
...
一旦我将其添加到依赖项数组中,代码导航就不再打开,因为它将直接触发效果并再次关闭


这是正确的方法吗?有没有更好的方法来防止不必要的渲染?

据我从您的代码中了解,您实际上不需要检查
mobileOpen
是否为真。我猜您想要的是将
mobileOpen
设置为假,无论该效果何时触发。我相信您'如果您像这样更新代码,就可以了:

useEffect(() => {
  setMobileOpen(false);
  main.current?.scrollTo(0, 0);
}, [pathname, main])

如果出于某种原因仍需要检查
mobileOpen
是否具有真实值,则可以使用
setMobileOpen((prevState)=>{…})
语法。

您可以跟踪
useRef
pathname
的上一个值,并比较路径名是否已更改。为什么需要
mobileOpen
。当您的路径名更改时,您的
useffect
会自动运行?是的,它会自动运行。但我不想通过将状态设置为每次都是false。因为有时它不是false。对于纯应用程序逻辑,我确实不需要知道mobileOpen的状态!但是:我想保存一些不必要的渲染。也许我必须以不同的方式问我的问题:您的代码将调用setMobileOpen(false)即使MobilePen已经为false。这将导致组件重新加载。不进行不必要的重新加载不是更好吗?实际上,如果MobilePen的值不变,它也不会重新加载。类组件就是这样,但函数组件的useState钩子提供了另一种方法。当设置相同的val时ue(==保持true)为状态,它不会触发重新渲染。您可以检查此代码沙盒以测试: