【问题标题】:'history', no-restricted-globals, and window.history'history'、无限制全局变量和 window.history
【发布时间】:2019-11-05 05:15:05
【问题描述】:

所以我在使用 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 本身不起作用?

“历史”究竟是什么? 'window' 做什么来解决这个问题?

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

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    您遇到的 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

    Window.history 只读属性返回对 History 对象的引用,该对象提供了用于操作浏览器会话历史记录(在当前页面加载到的选项卡或框架中访问的页面)的接口。

    例如

    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
    

    【讨论】:

      猜你喜欢
      • 2019-02-26
      • 2017-12-12
      • 1970-01-01
      • 2019-06-05
      • 2013-01-06
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 2019-01-27
      相关资源
      最近更新 更多