“历史对象是可变的”是什么意思?

问题描述 投票:0回答:1

我对React Router文档有疑问,它说“历史对象是可变的”并给出了如下示例:

历史对象是可变的。因此建议访问

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个回答
2
投票

“Mutable history

表示您只有 1 history
 对象,该对象在创建后会发生突变(例如更改)。这意味着如果您将来使用 
history
 对象进行比较,如下所示,您将
始终收到 false
。这是因为 
this.props.history
prevProps.history
 指向 
sameonly history
 对象(例如它们是相等的)。有关对象比较的更多信息
这里

// INCORRECT, will *always* be false because history is mutable. const locationChanged = this.props.history.location !== prevProps.history.location;
    
© www.soinside.com 2019 - 2024. All rights reserved.