使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
当前回答
反应路由器dom:5.1.2
该网站有3个页面,所有页面都在浏览器中动态呈现。尽管页面从未刷新,请注意React Router在浏览网站时保持URL最新。这保留浏览器历史记录,确保后面的内容按钮和书签工作正常Switch查看所有子项元素,并渲染其路径为与当前URL匹配。随时使用您有多条路线,但只需要一条一次渲染一个
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>
);
}```
其他回答
更新:2022:使用useNavigate的React Router v6.6.1
useHistory()钩子现已弃用。如果您使用的是React Router 6,编程导航的正确方法如下:
import { useNavigate } from "react-router-dom";
function HomeButton() {
const navigate = useNavigate();
function handleClick() {
navigate("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
带挂钩的React Router v5.1.0
如果您使用的是React>16.8.0和功能组件,则React Router>5.1.0中有一个新的useHistory钩子。
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>
);
}
反应路由器v4
使用React Router的v4,有三种方法可以用于组件内的编程路由。
使用withRouter高阶组件。使用合成并渲染<Route>使用上下文。
React Router主要是历史库的包装器。历史记录处理与浏览器窗口的交互。历史记录为您提供浏览器和哈希历史记录。它还提供了一个内存历史,对于没有全局历史的环境非常有用。这在使用Node进行移动应用程序开发(react native)和单元测试时特别有用。
历史记录实例有两种导航方法:推送和替换。如果您将历史记录视为一个访问位置数组,push将向数组中添加一个新位置,replace将用新位置替换数组中的当前位置。通常,您在导航时需要使用push方法。
在React Router的早期版本中,您必须创建自己的历史实例,但在v4中,<BrowserRouter>、<HashRouter>和<MemoryRouter>组件将为您创建浏览器、哈希和内存实例。React Router使与路由器关联的历史实例的财产和方法通过路由器对象下的上下文可用。
1.使用withRouter高阶组件
withRouter高阶组件将注入历史对象作为组件的属性。这允许您访问push和replace方法,而不必处理上下文。
import { withRouter } from 'react-router-dom'
// this also works with react-router-native
const Button = withRouter(({ history }) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
))
2.使用合成并渲染<Route>
<Route>组件不仅仅用于匹配位置。您可以渲染无路径路线,它将始终与当前位置匹配。<Route>组件传递与withRouter相同的属性,因此您可以通过历史属性访问历史方法。
import { Route } from 'react-router-dom'
const Button = () => (
<Route render={({ history}) => (
<button
type='button'
onClick={() => { history.push('/new-location') }}
>
Click Me!
</button>
)} />
)
3.使用上下文*
但你可能不应该
最后一个选项是只有当您觉得使用React的上下文模型时才应该使用的选项(React的context API在v16中是稳定的)。
const Button = (props, context) => (
<button
type='button'
onClick={() => {
// context.history.push === history.push
context.history.push('/new-location')
}}
>
Click Me!
</button>
)
// you need to specify the context type so that it
// is available within the component
Button.contextTypes = {
history: React.PropTypes.shape({
push: React.PropTypes.func.isRequired
})
}
1和2是实现的最简单的选择,因此对于大多数用例来说,它们是最好的选择。
对于React路由器v4+
假设在初始渲染过程中不需要导航(可以使用<Redirect>组件),这就是我们在应用程序中所做的。
定义返回null的空路由。这将允许您访问历史对象。您需要在定义路由器的顶层执行此操作。
现在,您可以在历史上做所有可以做的事情,如history.push()、history.replace()、history.go(-1)等。!
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">
<Route
render={({ history }) => {
routeHistory = history;
return null;
}}
/>
{/* Rest of the App */}
</HashRouter>
);
}
在基于类的组件中编程导航。
import { Redirect } from "react-router-dom";
class MyComponent extends React.Component{
state = {rpath: null}
const goTo = (path) => this.setState({rpath: path});
render(){
if(this.state.rpath){
return <Redirect to={this.state.rpath}/>
}
.....
.....
}
}
React路由器v2
对于最新版本(v2.0.0-rc5),推荐的导航方法是直接推到历史单例。您可以在组件外部导航文档中看到这一点。
相关摘录:
import { browserHistory } from 'react-router';
browserHistory.push('/some/path');
如果使用更新的react router API,则需要在组件内部使用this.props中的历史记录,以便:
this.props.history.push('/some/path');
它还提供pushState,但对于每个记录的警告,它都是不推荐的。
如果使用react router redux,它提供了一个推送功能,您可以这样调度:
import { push } from 'react-router-redux';
this.props.dispatch(push('/some/path'));
然而,这可能仅用于更改URL,而不是实际导航到页面。
对于已经使用React Router v6的用户,可以使用React Router提供的useNavigate钩子来完成。
使用此钩子进行导航非常简单:
import { generatePath, useNavigate } from 'react-router';
navigate(-1); // navigates back
navigate('/my/path'); // navigates to a specific path
navigate(generatePath('my/path/:id', { id: 1 })); // navigates to a dynamic path, generatePath is very useful for url replacements