React Routing Redirect onClick

喜夏-厌秋 提交于 2021-02-18 22:30:07

问题


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>

//Login.js

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

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

//AdminServices.js

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

回答1:


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`);
  };
};



回答2:


You can route by function by like this

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

Hope this help




回答3:


Simple, use NavLink instead of button

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

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

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




回答4:


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

P.S react router auth example




回答5:


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

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



来源:https://stackoverflow.com/questions/51393153/react-routing-redirect-onclick

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