问题描述
我使用的是 react-router,所以我在整个应用程序中使用 <Link/>
组件作为链接,在某些情况下,我需要根据用户输入动态生成链接,所以我需要类似 window.location
的东西,但没有页面刷新.
I'm using react-router, so I use the <Link />
component for my links throughout the app, in some cases I need to dynamically generate the link based on user input, so I need something like window.location
, but without the page refresh.
我发现了这个小笔记 - (https://github.com/rackt/react-router/issues/835) - 我尝试使用 this.context.router.transitionTo(mylink)
但我遇到了上下文问题...
I found this little note - (https://github.com/rackt/react-router/issues/835) - i tried using this.context.router.transitionTo(mylink)
but I'm having issues with context...
这让我(https://github.com/rackt/react-router/issues/1059),但是上下文返回和空对象,所以当我尝试做类似的事情时: this.context.router.transitionTo(mylink);
我得到 Cannot read属性 'transitionTo' of undefined
(如果我尝试在构造函数中执行类似 set this.context = context 的操作).
which led me to (https://github.com/rackt/react-router/issues/1059), however context returns and empty object, so when I try todo something like: this.context.router.transitionTo(mylink);
I get Cannot read property 'transitionTo' of undefined
(if I try to do something like set this.context = context within the constructor).
不要拖延,但我也厌倦了过多地弄乱上下文,因为它是故意没有记录的,因为它仍在进行中,所以我已经阅读了.
Not to drag on, but I'm also weary of messing too much with context as it is undocumented on purpose as it's still a work in progress, so I've read.
有没有人遇到过类似的问题?
Has anyone come across a similar issue?
推荐答案
在这里找到解决方案:https://github.com/rackt/react-router/issues/975,这里是:https://github.com/rackt/react-router/issues/1499
Found a solution here: https://github.com/rackt/react-router/issues/975, and here: https://github.com/rackt/react-router/issues/1499
在构造函数中需要:
class SidebarFilter extends React.Component {
constructor(props, context) {
super(props, context);
还需要添加一个静态属性:
Also need to add a static property:
SidebarFilter.contextTypes = {
router: React.PropTypes.func.isRequired
};
然后我可以打电话:
this.context.router.transitionTo(/path-to-link);
这篇关于如何使用 react-router 和 ES6 类模拟 window.location的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!