【问题标题】:What does it mean by "the history object is mutable"?“历史对象是可变的”是什么意思?
【发布时间】:2021-11-20 14:12:53
【问题描述】:

我对@9​​87654321@ 表示怀疑,它说“历史对象是可变的”,并给出了如下示例:

历史对象是可变的。因此建议访问 location 来自<Route> 的渲染道具,而不是来自 history.location。这可以确保你对 React 的假设是 在生命周期钩子中正确。例如:

class Comp extends React.Component {
  componentDidUpdate(prevProps) {
    // will be true
    const locationChanged =
      this.props.location !== prevProps.location;

    // INCORRECT, will *always* be false because history is mutable.
    const locationChanged =
      this.props.history.location !== prevProps.history.location;
  }
}

<Route component={Comp} />;

在上面的示例代码中,这两个地方不应该是===而不是!==吗?

【问题讨论】:

  • 这正是它所说的:历史对象是可变的,即它的值可以在不改变其身份的情况下改变。不,它是!==,因为正如变量名所暗示的那样,它正在检查位置中的更改

标签: reactjs react-router react-router-dom


【解决方案1】:

“可变 history 意味着您只有 1 个 history 对象,该对象在创建后会被变异(例如更改)。这意味着如果您以后使用history 对象进行如下比较,您将总是收到false。这是因为 this.props.historyprevProps.history 指向 sameonly history 对象(例如它们相等)。更多关于对象比较here :)

// INCORRECT, will *always* be false because history is mutable.
    const locationChanged =
      this.props.history.location !== prevProps.history.location;

【讨论】:

    猜你喜欢
    • 2015-12-03
    • 1970-01-01
    • 2015-11-01
    • 2015-02-18
    • 1970-01-01
    • 2011-06-12
    相关资源
    最近更新 更多