Javascript 反应路由重定向 onClick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51393153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:49:31  来源:igfitidea点击:

React Routing Redirect onClick

javascriptreactjsreact-router

提问by Yashank Varshney

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:

我一直在尝试在单击按钮时对另一个组件进行简单的重定向,但由于某种原因它不起作用。我想重定向到“/仪表板”并从登录显示 AdminServices,如下所示:

//index.js

//index.js

ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, 
    document.getElementById("root"));

//App.js

//App.js

     <Switch>
          <Route path="/" component={Login} />
          <Route path="/dashboard" component={AdminServices} />
        </Switch>

//Login.js

//登录.js

<Button
onClick={this.login}
>
</Button>

login = () =>{
    <Redirect to="/dashboard" />
  }

//AdminServices.js

//AdminServices.js

render(){
        return(
            <div>Test</div>
        );
    }

采纳答案by Abdullah

Simple, use NavLinkinstead of button

简单,使用NavLink代替按钮

import { NavLink } from 'react-router-dom'

<NavLink to="/dashboard"> Dashboard </NavLink>

https://reacttraining.com/react-router/web/api/NavLink

https://reacttraining.com/react-router/web/api/NavLink

回答by Adnan shah

You can route by function by like this

你可以这样按功能路由

  handleOnSubmit = () => {
  this.props.history.push(`/dashboard`);
  };

Hope this help

希望这有帮助

回答by Максим Подварков

<Switch>component render only the first route that matches. You just need to swap your <Route>components in <Switch>case and use @Adnan shahanswer to make redirect function.

<Switch>组件只渲染第一个匹配的路由。您只需要交换<Route>组件<Switch>以防万一并使用@Adnan shahanswer 来制作重定向功能。

P.S react router auth example

PS 反应路由器身份验证示例

回答by Zahid A.

This happened to me once I had missed importing the component to the route.js file.

一旦我错过了将组件导入到 route.js 文件中,就会发生这种情况。

You need to reference/import files from the component to the routefile.

您需要从组件引用/导入文件到路由文件。