为什么useEffect无法在window.location.pathname更改上运行?

时间:2019-10-17 23:57:03

标签: reactjs

为什么 useEffect 不能在window.location.pathname的更改上运行?我只记录过一次loc

在没有任何其他库的情况下更改路径名时如何运行 useEffect

  useEffect(() => {
    const loc = window.location.pathname
    console.log({ loc })
  }, [window.location.pathname])

2 个答案:

答案 0 :(得分:2)

我改编了 Rafael Mora 的答案,使其适用于整个位置对象,并使用 useIsMounted 方法在 Next.js 应用的前端工作,并添加了打字稿类型。

hooks/useWindowLocation.ts

import useIsMounted from './useIsMounted'
import { useEffect, useState } from 'react'


const useWindowLocation = (): Location|void => {
  const isMounted = useIsMounted()
  const [location, setLocation] = useState<Location|void>(isMounted ? window.location : undefined)

  useEffect(() => {
    if (!isMounted) return

    const setWindowLocation = () => {
      setLocation(window.location)
    }

    if (!location) {
      setWindowLocation()
    }

    window.addEventListener('popstate', setWindowLocation)

    return () => {
      window.removeEventListener('popstate', setWindowLocation)
    }
  }, [isMounted, location])

  return location
}

export default useWindowLocation

hooks/useIsMounted.ts

import { useState, useEffect } from 'react'

const useIsMounted = (): boolean => {
  const [isMounted, setIsMounted] = useState(false)
  useEffect(() => {
    setIsMounted(() => true)
  }, [])

  return isMounted
}

export default useIsMounted

答案 1 :(得分:0)

创建一个钩子,类似:

./<ANY>.framework/Headers/ANY.h:#define ANYUseUIWebView ANY_NAME_PASTE(ANY_PREFIX_NAME, ANYUseUIWebView)

然后在组件中像这样使用它:

Binary file ./<FRAMEWORK-NAME>.framework/<LIB-FILE>.a matches

当然,您必须在顶部组件中执行此操作。