繁体   English   中英

使用React-Router 3在React中的组件内部重定向

[英]Redirect inside a component in React with react-router 3

如何使用React Router 3在React组件中进行路由重定向?

如果我使用这样的“后卫”组件:

const GuardContainer = (props) => {

    const {ok} = isOk(props)

    if (!ok) {
        // Redirect here  to /not-ok      
        return null
    }

    return <WrappedComponent {...props}/>
}

然后React抱怨改变状态

在现有状态转换期间(例如在render或另一个组件的构造函数中)无法更新。

在React Router V4中,有一个<Redirect />组件,允许您进行渲染,它将导航到目标。 您可能可以使用browserHistory在V3中自己制作:

import React from 'react';
import { browserHistory } from 'react-router';

class Redirect extends React.Component {

  componentDidMount() {
    browserHistory.push(this.props.to);
  }

  render() {
    return <div />
  }

}

export default Redirect;

然后使用to="/not-ok"渲染它

if (!ok) {
  return <Redirect to="/not-ok" />;
}

试试看或类似的尝试。

来自react-router v3的决定:

import React from 'react';
    import { browserHistory } from 'react-router';

    export default function GuardContainer(props) {
        const {ok} = isOk(props);

        if (!ok) {
            // Redirect here  to /not-ok
            browserHistory.push('/not-ok');
        }

        return <WrappedComponent {...props} />
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM