【问题标题】:Use effect for every time that location.pathname changes每次 location.pathname 更改时使用效果
【发布时间】:2020-03-06 12:17:16
【问题描述】:

我有一个名为 nameScreen 的变量,每次 location.path 更改时我都需要更改我们的值:

<Typography variant="h6" noWrap>
    {nameScreen}
</Typography>

我试试:

const [nameScreen, setNameScreen] = useState('')

const location = useLocation();

useEffect(() => {
    changeTitleHeader()
        // eslint-disable-next-line react-hooks/exhaustive-deps
},[location.pathname])

  const changeTitleHeader = () => {
      if (location.pathname === '/home') {
        setNameScreen('Welcome to home!')
      }
      else if(location.pathname === '/users') {
          setNameScreen('Users')
      }
      else if(location.pathname === '/companies') {
        setNameScreen('Companies')
      }
  }

我需要每次我的location.pathname 更改时,此排版组件都有一个基于路线名称的新值。

location.pathname 更改时不会调用我的useEffect()。我该如何解决这个问题?

【问题讨论】:

  • 我想你正在使用路由器来路由你的路径。为什么不给每条路由添加一个带有标题的 prop 并在路由器中传递它而不是在容器中拥有一个状态

标签: reactjs react-router-dom


【解决方案1】:

您还需要在changeTitleHeader 函数中依赖location.pathname,而不仅仅是useEffect。该函数会记住 location.pathname 的初始值并且从不更新它,因此它不会在调用时执行任何新操作。

您可以为此目的使用useCallback。代码如下:

const changeTitleHeader = useCallback(() => { sameThing() }, [location.pathname]);

我在这里假设状态没有按预期更新,但如果您的 useEffect 没有真正触发,那么问题可能出在其他地方。希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 2017-11-26
    • 2021-02-06
    • 1970-01-01
    • 2013-10-27
    • 2020-12-09
    • 2016-01-27
    • 2012-12-19
    • 1970-01-01
    相关资源
    最近更新 更多