Link和hisroty.push两种跳转的区别
来源:6-2 登录注册-登录注册页面实现

慕粉3775984
2017-11-03
我尝试了用Link进行跳转到register页面
<Link to="/register"> Button type="primary" onClick="registerClick">注册</Button> </Link>
发现会重新渲染整个页面,包括没有改变的Logo组件,而history.push()却没有重新渲染Logo(或者是我肉眼无法分辨)这两种跳转有什么区别吗
写回答
1回答
-
慕瓜8449030
2017-11-03
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 来跳转
00
Redux+React Router+Node.js全栈开发
全网唯一的React 16+Redux+React Router4实战课程,学到手是你的真本领!
1822 学习 · 750 问题
相似问题