import { useNavigate } from "react-router-dom";
function Component() {let navigate = useNavigate();// Somewhere in your code, e.g. inside a handler:navigate("/posts");}
import { useNavigate } from "react-router-dom";
function SignupForm() {let navigate = useNavigate();
async function handleSubmit(event) {event.preventDefault();await submitForm(event.target);navigate("../success", { replace: true });// replace: true will replace the current entry in// the history stack instead of adding a new one.
}
return <form onSubmit={handleSubmit}>{/* ... */}</form>;}
React-Rout5.1.0+答案(使用钩子和React>16.8)
您可以使用useHistory挂钩函数组件和编程导航:
import { useHistory } from "react-router-dom";
function HomeButton() {let history = useHistory();// use history.push('/some/path') here};
React-路由器4.0.0+答案
在4.0及更高版本中,使用历史作为组件的道具。
class Example extends React.Component {// use `this.props.history.push('/some/path')` here};
import { useRouterHistory } from 'react-router'import { createHashHistory } from 'history'const appHistory = useRouterHistory(createHashHistory)({ queryKey: false });
export default appHistory;
并在任何地方使用它!
反应路由器(app.jsES6)的切入点:
import React from 'react'import { render } from 'react-dom'import { Router, Route, Redirect } from 'react-router'import appHistory from './app_history'...const render((<Router history={appHistory}>...</Router>), document.querySelector('[data-role="app"]'));
您在任何组件中的导航(ES6):
import appHistory from '../app_history'...ajaxLogin('/login', (err, data) => {if (err) {console.error(err); // login failed} else {// logged inappHistory.replace('/dashboard'); // or .push() if you don't need .replace()}})
import { withRouter } from 'react-router';
class Example extends React.Component {// use `this.props.router.push('/some/path')` here};
// Export the decorated classexport default withRouter(Example);
import { useHistory } from "react-router-dom";
function HomeButton() {const history = useHistory();
function handleClick() {history.push("/home");}
return (<button type="button" onClick={handleClick}>Go home</button>);}
import { withRouter } from 'react-router-dom'// this also works with react-router-native
const Button = withRouter(({ history }) => (<buttontype='button'onClick={() => { history.push('/new-location') }}>Click Me!</button>))
const Button = (props, context) => (<buttontype='button'onClick={() => {// context.history.push === history.pushcontext.history.push('/new-location')}}>Click Me!</button>)
// you need to specify the context type so that it// is available within the componentButton.contextTypes = {history: React.PropTypes.shape({push: React.PropTypes.func.isRequired})}
//using ES6import React from 'react';
class App extends React.Component {
constructor(props) {super(props)this.handleClick = this.handleClick.bind(this)}
handleClick(e) {e.preventDefault()/* Look at here, you can add it here */this.props.history.push('/redirected');}
render() {return (<div><button onClick={this.handleClick}>Redirect!!!</button></div>)}}
export default App;
import createBrowserHistory from 'history/createBrowserHistory'export default createBrowserHistory()
BasicComponent.js
import React, { Component } from 'react';import history from './history';
class BasicComponent extends Component {
goToIndex(e){e.preventDefault();history.push('/');}
render(){return <a href="#" onClick={this.goToIndex}>Previous</a>;}}
如果您必须从实际从Route组件呈现的组件导航,您还可以从props访问历史记录,如下所示:
BasicComponent.js
import React, { Component } from 'react';
class BasicComponent extends Component {
navigate(e){e.preventDefault();this.props.history.push('/url');}
render(){return <a href="#" onClick={this.navigate}>Previous</a>;}}
import {withRouter} from 'react-router-dom';
class Home extends Component {
componentDidMount() {this.props.history.push('/redirect-to');}}
export default withRouter(Home);
import createHistory from 'history/createBrowserHistory'
export default createHistory()
文件App.js/Route.jsx
import { Router, Route } from 'react-router-dom'import history from './history'...<Router history={history}><Route path="/test" component={Test}/></Router>
文件*another_file.js或还原文件
import history from './history'
history.push('/test') // This should change the URL and rerender Test component
import React from 'react';import { HashRouter, Route } from 'react-router-dom';
let routeHistory = null;
export function navigateTo(path) {if(routeHistory !== null) {routeHistory.push(path);}}
export default function App(props) {return (<HashRouter hashType="noslash"><Routerender={({ history }) => {routeHistory = history;return null;}}/>{/* Rest of the App */}</HashRouter>);}
const [redirect, setRedirect] = useState(false);const handleRedirect = useCallback(() => {let render = null;if (redirect) {render = <Redirect to="/redirectpush" push={true} />
// In order wait until committing to the DOM// and get back the button for clicking next timesetTimeout(() => setRedirect(false), 0);}return render;}, [redirect]);
return <>{handleRedirect()}<button onClick={() => setRedirect(true)}>Redirect push</button></>
import React from "react";import {BrowserRouter as Router,Switch,Route,Link} from "react-router-dom";
export default function BasicExample() {return (<Router><div><ul><li><Link to="/">Home</Link></li><li><Link to="/about">About</Link></li><li><Link to="/dashboard">Dashboard</Link></li></ul>
<hr />
<Switch><Route exact path="/"><Home /></Route><Route path="/about"><About /></Route><Route path="/dashboard"><Dashboard /></Route></Switch></div></Router>);}
// You can think of these components as "pages"// in your app.
function Home() {return (<div><h2>Home</h2></div>);}
function About() {return (<div><h2>About</h2></div>);}
function Dashboard() {return (<div><h2>Dashboard</h2></div>);}```
import { generatePath, useNavigate } from 'react-router';
navigate(-1); // navigates backnavigate('/my/path'); // navigates to a specific pathnavigate(generatePath('my/path/:id', { id: 1 })); // navigates to a dynamic path, generatePath is very useful for url replacements