关于react-router v4 官方示例中 Link 中 to 作为对象里的 state

最近在看 react-router v4api ,在 https://reacttraining.com/react-router/web/api/Link/to-object 中看到一段代码,

<Link to={{
  pathname: '/courses',
  search: '?sort=name',
  hash: '#the-hash',
  state: { fromDashboard: true }
}}/>

这里的state: { fromDashboard: true },我完全没看懂,
百度了很多,没有找到,
刚开始以为是点击这个 Link 时会改变 state 做了尝试,发现并不是,
我还看了 Link 的源码,也没有发现什么奥秘,
所以由于好奇心的驱使,我提出了这个问题,
想知道这个state到底是什么意思,或者是举例有错误?
求解答。

阅读 5.5k
3 个回答

原生的history.pushState()方法可以传入一个 state,有些浏览器会把它保存起来,重启浏览器的时候恢复 state:

state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.

The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts the browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.

https://developer.mozilla.org/en-US/docs/Web/API/History_API

state的内容都是自定义的。你可以在Link的pathname对应的Route的render或者children里面中的location对象拿到你自定义的state,然后做什么完全取决你

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题