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

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

Search for the keywords to learn more about each error.

我搜索了很多关于如何解决这个问题的方法,但我找到的答案都对我没有帮助,所以我求助于Stack overflow。

有人知道如何修复这个错误吗?我很感激我能得到的所有帮助。


当前回答

由于您正在使用react,我假设您正在使用检索路由器导航的useLocation()函数。 在这种情况下,将它分配给一个位置变量是很常见的,方法如下:

const location = useLocation();

然后,我打赌你会用它来检索location。pathname。 因为eslint将location作为window的一个元素进行检测。它将抛出no-restricted-globals错误编译。 为了修复这个问题,只需重命名变量如下:

const loc = useLocation();

查看下面描述它用法的tsx/jsx代码。

const loc = useLocation();
return (
    <div className="App">
        <div className="app-container">
            {loc.pathname !== '/login' && <Menu></Menu>}
            <div className="mid-container">
                <BodyContainer />
            </div>
        </div>
    </div>
);

另一方面,如果你正在使用window (location.pathname)的location属性,只需将window添加到它(window.location.pathname)就可以解决问题,就像接受的答案中解释的那样。

其他回答

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

也许您可以尝试将位置作为道具传递到组件中。 下面我使用……otherProps。这是展开运算符,有效但没有必要,如果你显式地传入你的props,它只是作为一个占位符用于演示。此外,研究解构来了解({location})来自哪里。

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

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


export withRouter(MyComponent);
/* eslint no-restricted-globals:0 */

是另一种替代方法

使用react-router-dom库。

如果你正在使用功能组件,从那里导入useLocation钩子:

import {useLocation} from 'react-router-dom';

然后将它附加到一个变量:

Const location = useLocation();

然后你可以正常使用它:

location.pathname

附注:返回的location对象只有五个属性:

{散列:“关键:“”,路径名:“/”搜索:“”,状态:undefined__,}

这是一个简单的,也许不是最好的解决方案,但它是有效的。

在你得到错误的那一行上面,粘贴这个:

// eslint-disable-next-line no-restricted-globals . //