簡體   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