问题
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