使用场景:
在用户进行一系列操作之后,满足条件之后需要自动跳转到其他的路由,而不是需要用户点击跳转按键操作,最常见的场景就是在登录页面设计的是时候,用户填写信息点击登录之后,数据发送给后台验证,返回验证通过的字段之后,这时页面不需要用户再点击,自动跳转到其他页面;这个时候使用react-router提供的Link组件是不满足需求的:
在网上找了一些方法:
参考:https://segmentfault.com/a/1190000013912862?utm_source=tag-newest
这里主要介绍一下子组件控制跳转时遇到的一种情况;刚好也是在上面的参考文档中没有具体测试提到的:
/** 父组件中,也是在react-router中page层次的组件中*/
render(){
return(
<div>
/** 登录页面的填写表单组件*/
<LoginForm />
</div>
);
}
/** LoginForm组件中*/
handleLogin = () => {
****
fetch(*****)
****
.then(res => {
if(res.status==='ok'){ // 登录信息验证通过
res.props.history.push('***其他路由');
}
}
)
}
在上面这种例子中,如果直接在组件中使用this.props.history.push('其他路由')的话,会有错误提示,提示history没有push属性,其实连history也没有;可以直接console.log(this.props)查看(我已经试过了);但是如果在page层次的组件中打印的话就可以发现会存在history,而且存在push等一系列操作的熟悉;所以可以在page层次的组件中传递下去history参数,然后就可以使用了:
/** 父组件中,也是在react-router中page层次的组件中*/
render(){
const { history } = this.props;
return(
<div>
/** 登录页面的填写表单组件*/
<LoginForm history = { history }/>
</div>
);
}
/** LoginForm组件中*/
handleLogin = () => {
const { history } = this.props;
****
fetch(*****)
****
.then(res => {
if(res.status==='ok'){ // 登录信息验证通过
history.push('***其他路由');
}
}
)
}