gpt4 book ai didi

javascript - “历史”、无限制全局变量和 window.history

转载 作者:行者123 更新时间:2023-11-29 22:55:19 25 4
gpt4 key购买 nike

所以我在 React 中遇到了一个问题,如果我尝试使用“历史”,我的代码将不会运行,并告诉我这是“意外使用 history no-restricted-global” .

我求助于 StackOverflow 以获得帮助,令人惊讶的是,我能够找到我正在处理的问题的答案。

另一个用途建议的修复非常有效,但现在我很困惑为什么它首先起作用。

使用 redux,我通过 mapDispatchToProps 调用了一个方法。我需要将“历史记录”作为传入的变量之一放入,以便我可以将用户重定向回他们所在的上一页。

最初,我尝试仅使用“历史记录”本身作为变量,但在尝试编译时会出现“无限制全局”错误,因此我求助于 StackOverflow。这是他们建议我尝试使用“window.history”的时候。起初我持怀疑态度,因为我认为这么简单的事情无法解决我的问题,但你瞧,它编译成功了。

props.addExperience(data, history);

对比

props.addExperience(data, window.history);

window.history 有效。有人可以解释为什么 window.history 有效但 history 本身不起作用吗?

“历史”到底是什么? “窗口”做了什么来解决这个问题?

编辑:this是我找到的原始 StackOverflow 帖子。虽然 Chasen Bettinger 能够解决这个问题,但他从未真正解释过为什么这个窗口。会解决这个问题。如果这里有人能做到这一点,那就太棒了。

最佳答案

您遇到的 linting 规则试图解决的问题是隐式引用全局对象上的属性是 easy source of bugs .例如:

var status = false;
if (status) {
console.log('status is actually truthy!');
}

这里,顶层的status实际上是指window.status,它必须始终是一个字符串;将 false 分配给它会导致 false 变成 'false'

如果 status 是具有该规则的受限全局,则只有在明确引用 window.status 时才能在顶层使用 status 。这样一来,很明显您故意引用了全局属性,这并非偶然。

当您引用 window.history 而不是 history 时,会发生同样的事情。例如,如果您在代码的前面定义了一个变量会怎么样

var history;

然后使用

props.addExperience(data, history);

linter 不确定您是在尝试引用全局对象上的属性,还是输入有误。因此,规则是让您明确指定该属性位于 window 上(或更正变量名称)。

至于window.history到底是什么,see MDN :

The Window.history read-only property returns a reference to the History object, which provides an interface for manipulating the browser session history (pages visited in the tab or frame that the current page is loaded in).

例如

history.back();     // equivalent to clicking back button
history.go(-1); // equivalent to history.back();
window.history.go(0); // refresh the current page
history.pushState(stateObj, "page 2", "bar.html"); // add an item to the history state

关于javascript - “历史”、无限制全局变量和 window.history,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56718921/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com