reactjs - 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 是什么,它是“/”,它是一个字符串。
解决方案
由于依赖数组为空,它只会在组件挂载时计算一次。如果添加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]);
推荐阅读
- javascript - 使用 Selenium 在 Headless Chrome 中全屏显示
- apache-flink - 如何在 flink 1.8 中检查 MapState 是否为空
- c++ - 模板化的虚拟成员函数是被禁止的,有替代方案吗?
- youtube-api - 为什么我超过了 Youtube Api v3 的配额
- python - BeatuifulSoup 解析逻辑 - 在运行代码之前检查图像是否存在
- jquery - href 使用 jquery 数据表传递多个参数 - 渲染和返回
- r - R:代码运行,但检查时返回“NA”
- git - 我应该如何分出两个工作项,一个是增强 master,另一个是增强第一个?
- docker - 使用 HAproxy 对两个 ngnix docker 容器进行负载平衡
- android - 关闭和打开通知通道后通知 setFullScreenIntent 停止运行