React组件中经常会用到this.props.history.push来进行页面的跳转,关于props.history,在项目里使用过程中有遇到一些相关的问题和知识,在这里记录一下。
下面为history的属性:
history.push
就像上面所说的,history.push经常会用来进行页面的跳转,当然前提是在路由中有写url对应的界面组件,比如在登录页面中要跳转到主界面,首先在路由中规定响应的组件:
ReactDOM.render(
<Router history={hist}>
<Switch>
<Route path="/login" component={LoginPage} />
<Route path="/register" component={RegisterPage} />
<Route path="/" component={Admin} />
<Route path="*" component={NotMatch} />
</Switch>
</Router>,
document.getElementById("root")
);
在登录组件中使用history进行跳转:
this.props.history.push("/");
但和state一样,要使用this的方法必须要先绑定this才可以。
另外,除了push还可以通过Link组件直接进行页面跳转,将Button放进Link中就可以实现点击Button进行页面跳转的效果,比如点击跳转到注册界面:
<Link to="/register">
<Button color="primary">注册</Button>
</Link>
history.location.pathname
下面为history.location的属性:
pathname是我们push到history中的最新的字符串,当我们跳转到登录界面后pathname指的就是“/login”。
之所以拿出这个来说是因为对于许多功能页面来说,因为我们使用dashboard将它们作为子界面在一个主界面框架中进行切换,它们的url均以“/”开始,因此index中会先识别“/”进入Admin,现在要实现:
- 如果我们直接进入“/”会自动跳转到“/tasksquare”。
- 如果我们进入其他以“/”开头的子界面就不会发生跳转,渲染出相应的子界面。
就可以通过pathname进行判断了:
if(this.props.history.location.pathname === "/"){
this.props.history.push("/tasksquare");
}
当不满足if时就会继续执行渲染出相应的子页面。
history.goBack
这个就很简单了,很明显是回退函数,可以返回之前push过的页面,当没有参数时默认返回到上一个界面,goback(-2)则是指返回到上上个界面,以此类推。但值得注意的是,这里的回退指的是“重新生成”,会像刷新页面一样重新执行React.Component的生命周期函数