Reactjs react router dom中的路径名正在更改,但当我将其放在if语句中时,它一直在说true

Reactjs react router dom中的路径名正在更改,但当我将其放在if语句中时,它一直在说true,reactjs,if-statement,react-router-dom,Reactjs,If Statement,React Router Dom,我正在制作一个react应用程序。我正在导入useLocation并将其放入变量位置。我正在检查pathname是否为NOT/它应该输出false,但它在每个页面中都一直显示true import React, { useState, useEffect } from "react"; import { useLocation } from "react-router-dom"; function Header() { const [inIndex, setInIndex] = useSt

我正在制作一个react应用程序。我正在导入useLocation并将其放入变量位置。我正在检查pathname是否为NOT/它应该输出false,但它在每个页面中都一直显示true

import React, { useState, useEffect } from "react";
import { useLocation } from "react-router-dom";

function Header() {
  const [inIndex, setInIndex] = useState();
  let location = useLocation();

  useEffect(() => {
    //Checks if location.pathname is not "/".
    if (location.pathname !== "/") setInIndex(false);
    else setInIndex(true);
  }, []);

  console.log(inIndex); //Keeps saying true

  return null;
}

export default Header;
提前谢谢你


编辑:我还检查了location.pathname是什么,它是/它是一个字符串。

由于依赖项数组为空,它在组件装载时只计算一次。如果将位置添加到效果的依赖项数组中,则在位置更改时将触发回调


由于依赖项数组为空,它在组件装载时只计算一次。如果将位置添加到效果的依赖项数组中,则在位置更改时将触发回调


您是否已尝试订阅钩子中location.pathname的更改?:

  useEffect(() => {
    //Checks if location.pathname is not "/".
    setInIndex(location.pathname === "/")
  }, [location.pathname]);

另外,您实际上不需要if语句,因为它会计算为常规bool。

您是否尝试订阅钩子中location.pathname的更改

  useEffect(() => {
    //Checks if location.pathname is not "/".
    setInIndex(location.pathname === "/")
  }, [location.pathname]);

另外,您并不真正需要if语句,因为它会计算成常规bool。

实际上,条件必须是===而不是==实际上,条件必须是===而不是==
  useEffect(() => {
    //Checks if location.pathname is not "/".
    setInIndex(location.pathname === "/")
  }, [location.pathname]);