Javascript ui路由器onEnter钩子被多次激发
我正在将我的应用程序迁移到ui router 1.0.0,我遇到了嵌套状态的问题,当OneNet$transitions钩子触发的次数与该状态的父级(即嵌套的深度)相同时,无论我是否在钩子中过滤状态。这是预期的还是错误Javascript ui路由器onEnter钩子被多次激发,javascript,angularjs,angular-ui-router,Javascript,Angularjs,Angular Ui Router,我正在将我的应用程序迁移到ui router 1.0.0,我遇到了嵌套状态的问题,当OneNet$transitions钩子触发的次数与该状态的父级(即嵌套的深度)相同时,无论我是否在钩子中过滤状态。这是预期的还是错误 $stateProvider .state("root", { url: "/" }) .state("root.child", { url: "/child" }) .state("root.child.child", { url:
$stateProvider
.state("root", {
url: "/"
})
.state("root.child", {
url: "/child"
})
.state("root.child.child", {
url: "/child",
data: {
foo: "bar"
}
});
$transitions.onEnter(
{to: state => state.data && state.data.foo === "bar"},
transition =>
console.log(`on enter triggered`, transition.from(), transition.to())
);
$state.go("root.child.child");
在本例中,钩子被触发3次
以下是使用app.js检查输入按钮是否命中的方法。。在那里,你可以插入一个函数,比如
$rootScope.hitnenter=function(){})运行区域中的代码>。这应该比在配置区域更好。我在github上用同样的问题创建了一个问题,ui路由器的顶级贡献者christopherthielen给了我一个关于这个问题的全面答案,我必须在这里发布,以防有人遇到同样的问题
这是基于您如何编写钩子的预期。onEnter
hook是基于状态的。处理onEnter
的伪代码如下:
最初进入root.child.child
时,会输入三种状态:root
,root.child
,root.child
您的条件是{to:state=>state.data&&state.data.foo===“bar”}
,它与输入的三个状态中的每一个都匹配。这是因为尽管输入了三个状态,但只有一个“to state”,即root.child.child
。该州的数据具有foo:'bar'
数据,因此它匹配
您应该将标准更改为使用输入
,而不是输入
{ entering: state => state.data && state.data.foo === 'bar' }
这是最新的提琴:
其他一些可能有效的方法:
将onEnter
放在状态本身上
.state("root.child.child", {
url: "/child",
data: {
foo: "bar"
},
onEnter: ($transition$, $state$) => do something specific when entering root.child.child
});
如果输入的任何状态都有数据,则每次转换执行一次操作。foo=='bar'
$transitions.onStart({ entering: state => state.data && state.data.foo === 'bar' }, trans =>
// do something
我认为你的答案与我的问题无关:(你在运行部分添加了你的代码吗?有一个函数应该只启动一次。。。