已有代码:
this.state.curUserInfo.isLogin ? <Redirect to={{ pathname: ROUTE_PREFIX.MAIN }} /> : <Redirect to={{ pathname: ROUTE_PREFIX.LOGIN }} /> ); |
希望在Redirect到Login时,传递一个callback函数作为参数。
react-router v4 redirect parameter
reactjs – React Router v4 Redirect with parameters – Stack Overflow
How to get query parameters in react-router v4 – Stack Overflow
javascript – React Router v4 Redirect not working – Stack Overflow
<Redirect /> can’t convert additional parameters. · Issue #4919 · ReactTraining/react-router
react-router v4 redirect pass function
react-router v4 pass function as parameter
react-router pass function as parameter
Access Route Params in React Router v4 | Jake Trent
https://jaketrent.com/post/access-route-params-react-router-v4/
How do I pass props in react router v4? – Stack Overflow
https://stackoverflow.com/questions/42893669/how-do-i-pass-props-in-react-router-v4
结果出错:
【已解决】React-RouterRedirect传递参数出错:Uncaught DOMException Failed to execute replaceState on History
【总结】
React-router v4中,对于Redirect或Link传递参数的话,可以通过path中的/xxx/para1之类的方式传递普通的字符串级别的参数。
但是此处如果想要传递额外的,对象或函数(比如传递一个登录后调用的回调函数)的话:
经过测试,函数是没法传递的
但是其他类型的参数,包括string,bool,Date等,都是可以的。
写法是:
state = { curUserInfo : { isLogin: false, name: ”, roleName: ”, loginTime: new Date() } }; <Redirect to={ { pathname: ROUTE_PREFIX.LOGIN, state: { curUserInfo: this.state.curUserInfo } } }/> |
路由定义为:
import React, { Component } from ‘react’; import { BrowserRouter as Router, Route, Link, Switch } from ‘react-router-dom’; import Index from ‘./index/index’; import Login from ‘./login/login’; import Main from ‘./main/main’; <Router basename={SLASH_PUBLIC_PATH}> <Switch> <Route exact path={ROUTE_PREFIX.INDEX} component={Index} /> <Route exact path={ROUTE_PREFIX.LOGIN} component={Login} /> <Route exact path={ROUTE_PREFIX.MAIN} component={Main} /> </Switch> </Router> |
即可在Login中通过:
this.props.location.state.curUserInfo获得对应的这个对象的参数。
export default class Login extends Component { state = { curUserInfo: EMPTY_USER_INFO }; constructor(props) { super(props); console.log(`Login constructor`); console.log(this.props); console.log(this.props.location); console.log(this.props.location.state); this.state.curUserInfo = this.props.location.state.curUserInfo; console.log(this.state.curUserInfo); 。。。 } |