最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【已解决】React-router v4的Redirect如何传递函数或对象作为参数

ReactJS crifan 6406浏览 0评论

已有代码:

      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);
。。。
 }

转载请注明:在路上 » 【已解决】React-router v4的Redirect如何传递函数或对象作为参数

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
82 queries in 0.192 seconds, using 22.12MB memory