react-router-dom 通过Link传值的坑人表现!

react-router-dom 通过Link传值的坑人表现!

link 可以通过以下方式传递到下一个路由:

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

在下一个页面可以这样取到值 (通过props.location.state 取值)

class CompName extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      param:props.location.state,
      search:props.location.search,
 }; 
 console.log("state-----:",this.props) }
}


------------------------但是-----------------------------

如果在Link里面加个 target="_blank", 这样的话, state里面的值就是undefined

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


不明白这是个什么设计, 猜想可能是: 在新窗口打开的话, 已经脱离了当前的页面state, (相当于window.open新窗口了吗?) , 这样就已经不是单页面应用了???

所以React如果想要在新窗口打开的页面之间传递参数, 还是老实的用search/hash这些方法吧 !

DEMO源码: https://download.csdn.net/download/cen_cs/10555893

猜你喜欢

转载自blog.csdn.net/cen_cs/article/details/78426164
今日推荐