请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

Link和hisroty.push两种跳转的区别

我尝试了用Link进行跳转到register页面

<Link to="/register">
    Button type="primary" onClick="registerClick">注册</Button>
</Link>

发现会重新渲染整个页面,包括没有改变的Logo组件,而history.push()却没有重新渲染Logo(或者是我肉眼无法分辨)这两种跳转有什么区别吗

正在回答 回答被采纳积分+3

1回答

慕瓜8449030 2017-11-03 18:06:46

Link 和 history 其实没有特别本质的区别 直接给你看下 Link 的代码

class Link extends React.Component {

render() {
    const { replace, to, innerRef, ...props } = this.props // eslint-disable-line no-unused-vars

    invariant(
    this.context.router,
    'You should not use <Link> outside a <Router>'
    )

    const { history } = this.context.router
    const location = typeof to === 'string' ? createLocation(to, null, null, history.location) : to

    const href = history.createHref(location)
    return <a {...props} onClick={this.handleClick} href={href} ref={innerRef}/>
}
}

其实 handleClick的代码

handleClick = (event) => {
  if (this.props.onClick)
  this.props.onClick(event)

  if (
  !event.defaultPrevented && // onClick prevented default
  event.button === 0 && // ignore everything but left clicks
  !this.props.target && // let browser handle "target=_blank" etc.
  !isModifiedEvent(event) // ignore clicks with modifier keys
  ) {
  event.preventDefault()

  const { history } = this.context.router
  const { replace, to } = this.props

  if (replace) {
     history.replace(to)
  } else {
    history.push(to)
  }
  }
}

其实核心还是 replace 或者 push 来跳转


0 回复 有任何疑惑可以回复我~
问题已解决,确定采纳
还有疑问,暂不采纳
Redux+React Router+Node.js全栈开发
  • 参与学习       1822    人
  • 解答问题       750    个

全网唯一的React 16+Redux+React Router4实战课程,学到手是你的真本领!

了解课程
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号