如何理解react-router官网写的“history is mutable”?this.props.location与this.props.history.location有什么区别?

tech2026-01-01  2

1. 关于this.props.location与this.props.history.location该用哪个?

- 简单粗暴的结论

简单说就是, 😯 两者的区别就是this.props.location更可靠 👌 so, 最好直接用this.props.location,特别是在react 生命周期钩子函数中(如果在生命周期函数中用this.props.history.location可能得不到你期望的值)

- react-router官网中的描述

react-router官网中在描述history时说: history is mutable

在描述location时又有这样一句话:a location object is never mutated so yu can use it in the lifecycle hooks…

👆 就是官网推荐你直接通过this.props.location来获取location

如果不想知道为什么,this is the end ~ 如果有兴趣了解,就继续往下看吧


2. 用实例来理解history is mutable

现在我有如下配置, 【path: /myurl 】— 对应 — 【 React组件: myUrl 】

<Route path='/myurl' component={MyUrl} />;

该路由对应的组件是这样的:

class MyUrl extends React.Component { componentWillReceiveProps(nextProps) { // nextProps.location vs this.props.location // nextProps.history.location vs this.props.history.location } componentDidUpdate (prevProps) { // prevProps.location vs this.props.location // prevProps.history.location vs this.props.history.location } }

假设我要跳转到地址:

http://localhost:8002/myproject/#/myurl?id=1

那么我需要执行以下代码跳转:

this.props.history.push({ pathname: '/myurl', search:'id=1', state: { fromSource: 1 }, });

接下来就重点看看上面两个生命周期函数中,props.location及props.history.location的取值

在 componentWillReceiveProps 中

对于 nextProps, location 的值(不管是从nextProps.location,还是从nextProps.history.location中取), 我们都期望它是变化后的值

对于 this.props 中, location 的值,我们期望它是原来的值(暂未发生变化的)

于是可以把该生命周期函数中,location的值打出来,跟我们期望值一对比(如下表):

location实际打印的值期望的值是否符合预期nextProps.location我们都期望location是变化后的值yesnextProps.history.location我们都期望location是变化后的值yesthis.props.location我们期望location是原来的值(暂未发生变化的)yesthis.props.history.location我们期望location是原来的值(暂未发生变化的)NO!!!

这样问题就来了,用history.location取到的值是不可靠的。 这也就是为什么react-router文档中说,history是易变的,推荐使用location.

官网链接: https://reactrouter.com/core/api/history/history-is-mutable.

同理可知,

在 componentDidUpdate 中 prevProps 中的 loaction 应该是变化之前的, this.props 中的 location 应该是变化之后的, location实际打印的值期望的值是否符合预期prevProps.location我们期望location是原来的值(did update之前的)yesprevProps.history.location我们期望location是原来的值(did update之前的)NO!!!this.props.location我们都期望location是变化后的值yesthis.props.history.location我们都期望location是变化后的值yes

总结一下,我们会发现: props.history.location是易变的,它的值是变化之后的值。 比如:

componentWillReceiveProps 中, nextProps.history.location与 this.props.history.location的值都是变化之后的componentDidUpdate 中, prevProps.history.location与 this.props.history.location的值也都是变化之后的

结论: props.history.location是不可靠的,有时候它的值与我们预期的不同,容易出错,因此,推荐使用props.location

最新回复(0)