反应路由重定向 onClick [英] React Routing Redirect onClick
本文介绍了反应路由重定向 onClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试在单击按钮时简单地重定向到另一个组件,但由于某种原因它不起作用.我想重定向到/dashboard"并从登录显示 AdminServices,如下所示:
Ive been trying to do a simple redirect to another component on button click, but for some reason it doesnt work.I want to redirect to '/dashboard' and display AdminServices from login as follows:
//index.js
ReactDOM.render(<BrowserRouter><App /></BrowserRouter>,
document.getElementById("root"));
//App.js
<Switch>
<Route path="/" component={Login} />
<Route path="/dashboard" component={AdminServices} />
</Switch>
//登录.js
<Button
onClick={this.login}
>
</Button>
login = () =>{
<Redirect to="/dashboard" />
}
//AdminServices.js
//AdminServices.js
render(){
return(
<div>Test</div>
);
}
推荐答案
代替使用 props.history,更好的方法是使用 useHistory 钩子,如下所示:
Instead of using the props.history, a better way is using the useHistory hook like below:
import { useHistory } from 'react-router-dom'
const MyComponent = (props) => {
const history = useHistory();
handleOnSubmit = () => {
history.push(`/dashboard`);
};
};
这篇关于反应路由重定向 onClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文