gpt4 book ai didi

javascript - ui-router onEnter 钩子(Hook)多次触发

转载 作者:太空宇宙 更新时间:2023-11-04 16:08:59 26 4
gpt4 key购买 nike

我正在将我的应用程序迁移到 ui-router 1.0.0,当 onEnter $transitions 钩子(Hook)触发多次时,我遇到了嵌套状态的问题,状态有多少个父级(即嵌套的深度),无论我是否过滤我的钩子(Hook)中的状态。这是预期的结果还是错误?

$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");

在此示例中,钩子(Hook)被触发 3 次。

这是fiddle .

最佳答案

我在 github 上创建了一个具有相同问题的问题,ui-router 的顶级贡献者 christopherthielen 给了我这个问题的全面答案,我有义务在这里发布,以防有​​人遇到这个问题同样的问题。

<小时/>

根据您对钩子(Hook)的编码方式,这是预期的。 onEnter hook 是基于状态的。用于处理onEnter的伪代码如下:

最初访问root.child.child时正在输入三种状态:root , root.child , root.child.child .

您的条件是{ to: state => state.data && state.data.foo === "bar" }其中与输入的三个状态中的每一个相匹配。这是因为虽然进入了三个状态,但只有一个“要状态”,即 root.child.child 。该州的数据为foo: 'bar'数据,因此匹配。

您应该更改您的标准以使用 entering而不是to .

{ entering: state => state.data && state.data.foo === 'bar' }

这是更新的 fiddle :https://jsfiddle.net/2m63pvqb/1/

其他一些可能有效的方法:

onEnter关于国家本身

  .state("root.child.child", {
url: "/child",
data: {
foo: "bar"
},
onEnter: ($transition$, $state$) => do something specific when entering root.child.child
});

如果输入的任何状态有 data.foo === 'bar',则每次转换执行一次操作

   $transitions.onStart({ entering: state => state.data && state.data.foo === 'bar' }, trans => 
// do something

关于javascript - ui-router onEnter 钩子(Hook)多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41659386/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com