[英]How do I use React Router Dom to navigate to a new page as a result of a Switch Case?
Essentially when a form is submitted I want the page to navigate to a different page as a result from a switch statement.本质上,当提交表单时,我希望页面根据 switch 语句导航到不同的页面。
switch (real_input_value()) {
case 'Help':
console.log('Displaying list of available commands')
user_input_resultsHelp()
<Link to="/"/>
break;
}
All the components in react-router-dom
have to go into the html area and not the javascript area, so how do I navigate to a new page using javascript inside of this switch
statement? react-router-dom
中的所有组件都必须将 go 放入 html 区域而不是 javascript 区域,那么如何在这个switch
语句中使用 javascript 导航到新页面?
Component code:组件代码:
const App = () => {
const input_command_logic = (e) => {
e.preventDefault();
switch (real_input_value()) {
case 'Help':
console.log('Displaying list of available commands')
user_input_resultsHelp()
<Link to="/"/>
break;
}
return()
Since the switch
statement is a form
element's onSubmit
callback it will need to issue an imperative navigation action.由于
switch
语句是form
元素的onSubmit
回调,因此它需要发出命令式导航操作。 For this import and use the useNavigate
hook to access the navigate
function in the component, and issue the navigation action in the handler.对于此导入并使用
useNavigate
挂钩访问组件中的navigate
function,并在处理程序中发出导航操作。
Example:例子:
import { ..., useNavigate } from 'react-router-dom';
...
const MyComponent = () => {
const navigate = useNavigate();
...
submitHandler = event => {
event.preventDefault();
...
switch (real_input_value()) {
...
case 'Help':
console.log('Displaying list of available commands')
user_input_resultsHelp()
navigate("/");
break;
...
}
};
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.