reactjs 无受限全局变量

mec1mxoz  于 2022-12-12  发布在  React
关注(0)|答案(8)|浏览(126)

我正在使用React和Redux开发一个Web应用程序,当我启动我的项目时,我得到了这个:

Line 13:  Unexpected use of 'location'  no-restricted-globals

Search for the keywords to learn more about each error.

我搜索了很多关于如何解决它的问题,但我找到的答案都没有帮助我,所以我转向了堆栈溢出。
有人知道如何修复这个错误吗?我很感激所有我能得到的帮助。

o4hqfura

o4hqfura1#

尝试在location之前添加window(即window.location)。

qvtsj1bj

qvtsj1bj2#

这是一个简单的,也许不是最好的解决方案,但它的工作。
在您收到错误消息的行上方,粘贴以下内容:
// eslint-disable-next-line no-restricted-globals

b91juud3

b91juud33#

使用react-router-dom库。
如果您使用的是功能组件,则从此处导入useLocation hook:
import { useLocation } from 'react-router-dom';
然后将其追加到变量:
Const location = useLocation();
然后,您可以正常使用它:
location.pathname
另外:返回的location对象只有五个属性:
{ hash: "", key: "", pathname: "/" search: "", state: undefined__, }

qxsslcnc

qxsslcnc4#

也许你可以尝试将location作为一个prop传入组件。下面我使用... otherProps。这是spread操作符,如果你显式地传入props,它是有效的,但不是必需的,它只是作为一个保持器用于演示目的。另外,研究解构以了解({ location })来自哪里。

import React from 'react';
import withRouter from 'react-router-dom';

const MyComponent = ({ location, ...otherProps }) => (whatever you want to render)

export withRouter(MyComponent);
c2e8gylq

c2e8gylq5#

这是eslint问题。我在输入值中使用name而没有定义name状态变量时也发生了同样的问题。
eslint有一个我们不能使用的限制词列表。我很好奇,发现了这个eslint-restricted-globals npm package
浏览器中的一些全局变量很可能会被无意将其用作全局变量的人使用,如status、name等。由于eslint认为它们是有效的全局变量,因此在出现错误时不会发出警告。

var restrictedGlobals = require("eslint-restricted-globals");

console.log("restricted ", restrictedGlobals);

这是eslint限制词的列表
0:“添加事件监听器”1:“模糊”2:“关闭”3:“关闭”4:“确认”5:“默认状态”6:“事件”7:“外部”8:“默认状态”9:“查找”10:《焦点访谈》11:“帧元素”12:“框架”13:《尚书》卷十四:“内部高度”15:“内部宽度”16:“长度”17:“位置”18:“位置栏”19:“菜单栏”20:“移动”21:“移动到”22:“姓名”23:“onblur”24:“出现错误”25:“聚焦”26:“加载”27:“调整大小”28:“卸载”29:“打开”30:“开启器”31:“歌剧”32:“外部高度”33:“外部宽度”34:“页面X偏移量”35:“页面Y偏移量”36:“父母”37:“打印机”38:“删除事件监听器”39:“调整大小依据”40:“调整大小为”41:“屏幕”42:“屏幕左”43:“屏幕顶部”44:“屏幕X”45:“屏幕Y”46:“卷轴”47:“滚动条”48:“滚动”49:“滚动到”50:“scrollX”51:“scrollY”52:“自我”53:“状态”54:“状态栏”55:“停止”56:“工具栏”57:“顶部”

tcomlyy6

tcomlyy66#

下午好,只需在文件顶部复制以下行:
/* eslint-disable no-restricted-globals */
这将允许您在该特定文件上全局禁用eslint规则。

fbcarpbf

fbcarpbf7#

就这样解构locaton:({location}) .

1cosmwyk

1cosmwyk8#

/* eslint no-restricted-globals:0 */

是另一种替代方法

相关问题