首页 > 解决方案 > react-router-dom 中的 useLocation().pathname 正在改变,但是当我把它放在 if 语句中时,它一直说是真的

问题描述

我正在制作一个反应应用程序。我正在导入 useLocation 并将其放入变量(位置)中。我正在检查路径名是否不是“/”它应该输出假,但它在每一页中都说真。

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 是什么,它是“/”,它是一个字符串。

标签: reactjsif-statementreact-router-dom

解决方案


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

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);
  }, [location]); // <-- add location to dependency array

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

  return null;
}

export default Header;

注意:您也可以只保存原始条件测试的逆,因为您在条件为真时设置为假。

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

推荐阅读