【问题标题】:history react router not working in class components历史反应路由器在类组件中不起作用
【发布时间】:2021-08-08 17:22:11
【问题描述】:

我正在为我的应用程序使用 React JS。

我正在使用 React 路由器。

我在 react 路由器中使用历史 API。

这是我的代码:

import MyComponentA from './MyComponentA';

function NavBar(){

    return(
        <Router>
            <Switch>
                <Route exact path="/somelink/abc" component={MyComponentA} />
            </Switch>
        </Router>
    );

}

export default NavBar;



class SomeClass extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            passCode: {
                email: "",
                password: ""
            },
            errorMessage: ''
        };
    }



    login = async (email) =>{
        let result;
        let authorized;
        

        if(this.state.passAccount.email === email && this.state.passAccount.password === result.data.OTPCode){
            console.log(`Permisson Granted!`);
            authorized = true;  

            //Redirect to another page
            this.props.history.push("/shipping/request");  //not working

        }else{
            console.log(`Permisson Denied!`);
            authorized = false;

        }
        

    }
    
    
    render(){
        return(
            <>
            button onClick={() => this.login(String(this.state.passAccount.email))}>Sign In</Button>
            </>
        );
    }
    
}


export default SomeClass;

我的问题: 我希望当我单击登录按钮时,它会将我重定向到以下端点: "/somelink/abc"

我做了以下,但没有任何工作:

this.props.history.push("/somelink/abc");

我也用过: this.context.history.push("/somelink/abc");

什么原因,没有重定向到页面?

【问题讨论】:

    标签: javascript reactjs react-redux react-router


    【解决方案1】:

    您可以通过 withRouter 高阶组件访问历史对象的属性和最接近的匹配项。 withRouter 将在渲染时将更新的匹配、位置和历史道具传递给包装的组件。试试这个:

    import { withRouter } from 'react-router';
    
    export default withRouter(SomeClass);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 2016-05-28
      • 2020-10-08
      • 2021-04-03
      • 2018-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多