【问题标题】:ui-router onEnter hook fired multiple timesui-router onEnter 钩子多次触发
【发布时间】:2017-05-30 06:54:36
【问题描述】:

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

$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 次。

这是fiddle。

【问题讨论】:

    标签: javascript angularjs angular-ui-router


    【解决方案1】:

    使用 app.js 来检查是否按下了回车键。在那里你可以在运行区插入一个像$rootScope.hitEnter = function(){ }); 这样的函数。这应该比在配置区域中更好。

    【讨论】:

    • 我认为您的回答与我的问题无关 :(
    • 您是否在运行部分中添加了您的代码?一个函数应该只触发一次......
    【解决方案2】:

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


    这是预期的,具体取决于您对钩子的编码方式。 onEnter 挂钩是基于状态的。处理onEnter的伪代码如下:

    最初转到root.child.child 时,会进入三种状态:root、root.child、root.child.child。

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

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

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

    这是一个更新的小提琴: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 
    

    【讨论】:

      猜你喜欢
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 2019-11-16
      • 1970-01-01
      相关资源
      最近更新 更多