我对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} />;
===
而不是
!==
吗?
“Mutable history
”表示您只有 1
history
对象,该对象在创建后会发生突变(例如更改)。这意味着如果您将来使用
history
对象进行比较,如下所示,您将始终收到
false
。这是因为
this.props.history
和
prevProps.history
指向same 和 only
history
对象(例如它们是相等的)。有关对象比较的更多信息这里
// INCORRECT, will *always* be false because history is mutable.
const locationChanged =
this.props.history.location !== prevProps.history.location;