How to redirect in React

ε祈祈猫儿з 提交于 2021-02-18 17:16:13

问题


I have a react app that acts as a dashboard and displays links for different React applications. Users can select the application by clicking a button.
In short I need to redirect to a different URL based on user selection.

In the sample code below, trying to redirect to a URL using withRouter. However its giving the below error: TypeError: Cannot read property 'push' of undefined

I am using React 15.6.1.

index.js

render(
    <BrowserRouter>
        <Home />
    </BrowserRouter>, document.getElementById('app')
);

home.js

class Home extends React.Component {

    constructor(props) {
        super(props);
        this.loadApp1 = this.loadApp1.bind(this);
    }

    loadApp1() {
        this.props.route.push('/app1');
    }
    render() {
        return (
            <div>
                 <button onClick={this.loadApp1}>App1</button>
            </div>
        );
    }
}

export default withRouter(Home);

回答1:


You could use Link to do this:

import { Link } from react-router-dom;

Then,

<button><Link to="/app1">App1</Link></button>

Will route to the App1 route.

For an external site, you could do this:

   loadApp1() {
        window.location = "example.com";
    }



回答2:


Your loadApp1 should be

 loadApp1() {
    this.props.history.push('/app1');
}


来源:https://stackoverflow.com/questions/46679318/how-to-redirect-in-react

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!