使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
使用react router,我可以使用Link元素来创建由react route本地处理的链接。
我看到它在内部调用this.context.transitionTo(…)。
我想做导航。不是来自链接,而是来自下拉选择(例如)。我如何在代码中执行此操作?this.context是什么?
我看到了导航混合,但我可以在没有混合的情况下这样做吗?
当前回答
以下是最简单、最干净的方法,大约是当前的React Router 3.0.0和ES6:
使用ES6反应路由器3.x.x:
import { withRouter } from 'react-router';
class Example extends React.Component {
// use `this.props.router.push('/some/path')` here
};
// Export the decorated class
export default withRouter(Example);
或者,如果不是默认类,则导出如下:
withRouter(Example);
export { Example };
注意,在3.x.x中,<Link>组件本身使用router.push,因此您可以传递任何传递<Linkto=标记的内容,例如:
this.props.router.push({pathname: '/some/path', query: {key1: 'val1', key2: 'val2'})'
其他回答
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,而不是实际导航到页面。
更新: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 Router 3.0.0和ES6:
使用ES6反应路由器3.x.x:
import { withRouter } from 'react-router';
class Example extends React.Component {
// use `this.props.router.push('/some/path')` here
};
// Export the decorated class
export default withRouter(Example);
或者,如果不是默认类,则导出如下:
withRouter(Example);
export { Example };
注意,在3.x.x中,<Link>组件本身使用router.push,因此您可以传递任何传递<Linkto=标记的内容,例如:
this.props.router.push({pathname: '/some/path', query: {key1: 'val1', key2: 'val2'})'
在我的回答中,有三种不同的方法可以通过编程重定向到路由。已经介绍了一些解决方案,但下面的解决方案仅针对具有附加演示应用程序的功能组件。
使用以下版本:
反应:16.13.1反应时间:16.13.1反应路由器:5.2.0反应路由器dom:5.2.0字体:3.7.2
配置:
因此,首先解决方案是使用HashRouter,配置如下:
<HashRouter>
// ... buttons for redirect
<Switch>
<Route exact path="/(|home)" children={Home} />
<Route exact path="/usehistory" children={UseHistoryResult} />
<Route exact path="/withrouter" children={WithRouterResult} />
<Route exact path="/redirectpush" children={RedirectPushResult} />
<Route children={Home} />
</Switch>
</HashRouter>
从有关<HashRouter>的文档中:
一个<Router>,它使用URL的哈希部分(即window.location.hash)来保持UI与URL同步。
解决:
使用<Redirect>使用useState推送:
在功能组件(我的存储库中的RedirectPushAction组件)中使用,我们可以使用useState来处理重定向。棘手的是,一旦发生重定向,我们需要将重定向状态设置回false。通过使用带有0延迟的setTimeOut,我们等待React提交重定向到DOM,然后返回按钮,以便下次使用。
请在下面找到我的示例:
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 time
setTimeout(() => setRedirect(false), 0);
}
return render;
}, [redirect]);
return <>
{handleRedirect()}
<button onClick={() => setRedirect(true)}>
Redirect push
</button>
</>
从<Redirect>文档:
渲染<重定向>将导航到新位置。新位置将覆盖历史堆栈中的当前位置,就像服务器端重定向(HTTP 3xx)那样。
使用useHistory钩子:
在我的解决方案中,有一个名为UseHistoryAction的组件,它表示以下内容:
let history = useHistory();
return <button onClick={() => { history.push('/usehistory') }}>
useHistory redirect
</button>
useHistory钩子允许我们访问历史对象,它帮助我们以编程方式导航或更改路线。
使用withRouter,从道具获取历史记录:
创建了一个名为WithRouterAction的组件,显示如下:
const WithRouterAction = (props:any) => {
const { history } = props;
return <button onClick={() => { history.push('/withrouter') }}>
withRouter redirect
</button>
}
export default withRouter(WithRouterAction);
阅读路由器文档:
您可以通过withRouter高阶组件访问历史对象的财产和最接近的<Route>匹配项。无论何时渲染,withRouter都会将更新的匹配、位置和历史属性传递给包装组件。
演示:
为了更好地表示,我用这些示例构建了一个GitHub存储库,请在下面找到它:
React Router程序化重定向示例
随着React Router v4即将推出,现在有了一种新的实现方式。
import { MemoryRouter, BrowserRouter } from 'react-router';
const navigator = global && global.navigator && global.navigator.userAgent;
const hasWindow = typeof window !== 'undefined';
const isBrowser = typeof navigator !== 'undefined' && navigator.indexOf('Node.js') === -1;
const Router = isBrowser ? BrowserRouter : MemoryRouter;
<Router location="/page-to-go-to"/>
react lego是一个示例应用程序,展示了如何使用/更新react router,它包括导航应用程序的示例功能测试。