"key" 随 connected-react-router 在每条路线上发生的变化是什么?
What is the "key" which changes on every route change with connected-react-router?
当导航到路线的动作被触发时,动作会触发一个新状态,其中 router.location.pathname
根据浏览器的 history
变化。
另一个 属性 也发生了变化:router.location.key
,变成了一个新的随机字符串。
即使路径名本身没有更改(从页面本身单击 link 到页面),key
仍会更新。
key
属性 的目的是什么?在哪些情况下我希望我自己的状态有一个随机生成的 key
,它会在非常动作调度时更新?为什么它不是一个简单递增的数字?
connected-react-router
简单地存储来自 react-router
的位置对象,后者又使用 history 包创建位置对象。在 history
的自述文件中描述了 key
属性:
Locations may also have the following properties:
location.key - A unique string representing this location (supported in
createBrowserHistory and createMemoryHistory)
它在内部使用(例如在 https://github.com/ReactTraining/history/blob/master/modules/createBrowserHistory.js 中用于查找当前历史堆栈中的位置)并且应被视为 react-router
的实现细节。我怀疑随机密钥而不是递增序列号是实现唯一 ID 的最简单方法(您不必存储当前序列号)。
这会导致在再次访问时不必要地重新渲染当前路线,因为 props 发生了变化。解决该问题的一种方法是使用 React.memo
,并比较保持不变的 location.path
。但是如果你的组件接收到其他道具,你将不得不小心,所以将它们包括在比较中。
Each location gets a unique key. This is useful for advanced cases
like location-based scroll management, client side data caching, and
more. Because each new location gets a unique key, you can build
abstractions that store information in a plain object, new Map(), or
even locationStorage.
当导航到路线的动作被触发时,动作会触发一个新状态,其中 router.location.pathname
根据浏览器的 history
变化。
另一个 属性 也发生了变化:router.location.key
,变成了一个新的随机字符串。
即使路径名本身没有更改(从页面本身单击 link 到页面),key
仍会更新。
key
属性 的目的是什么?在哪些情况下我希望我自己的状态有一个随机生成的 key
,它会在非常动作调度时更新?为什么它不是一个简单递增的数字?
connected-react-router
简单地存储来自 react-router
的位置对象,后者又使用 history 包创建位置对象。在 history
的自述文件中描述了 key
属性:
Locations may also have the following properties:
location.key - A unique string representing this location (supported in createBrowserHistory and createMemoryHistory)
它在内部使用(例如在 https://github.com/ReactTraining/history/blob/master/modules/createBrowserHistory.js 中用于查找当前历史堆栈中的位置)并且应被视为 react-router
的实现细节。我怀疑随机密钥而不是递增序列号是实现唯一 ID 的最简单方法(您不必存储当前序列号)。
这会导致在再次访问时不必要地重新渲染当前路线,因为 props 发生了变化。解决该问题的一种方法是使用 React.memo
,并比较保持不变的 location.path
。但是如果你的组件接收到其他道具,你将不得不小心,所以将它们包括在比较中。
Each location gets a unique key. This is useful for advanced cases like location-based scroll management, client side data caching, and more. Because each new location gets a unique key, you can build abstractions that store information in a plain object, new Map(), or even locationStorage.