【问题标题】:Vuex Method-style Access GettersVuex 方法风格的访问 Getter
【发布时间】:2021-07-17 03:05:46
【问题描述】:

我有点难以理解以下 JS:

const store = new Vuex.Store({
  state: {
    todos: [
      { id: 1, text: '...', done: true },
      { id: 2, text: '...', done: false }
    ]
  },
getters: {
  // ...
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}
})

store.getters.getTodoById(2) // -> { id: 2, text: '...', done: false }

这两个代码sn-ps取自Vuex官方文档on Method Style Access for Getters。

现在我不明白的是,代码的第二部分如何输出注释中的值?可能是我没理解 JS 函数?

我相信输出会是:

(id) => {
  return state.todos.find(todo => todo.id === id)
}

所以实际上是返回的第二个函数,因为在他们使用的调用中,我没有看到两个 '()()',我也不明白函数从哪里接收 'state' 变量。

我想请求解释一下,我是否错过了 JS 中的某些内容,或者这是 Vuex 特定的内容?

【问题讨论】:

标签: javascript function vue.js vuex


【解决方案1】:

curried 箭头函数示例见此:https://stackoverflow.com/a/32787782/11375753


但是,当我们考虑到 vuex getter 方法时,它的工作原理如下。

getters: {
  getTodoById: (state) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

  • 我们在名为getToboById 的属性中定义了一个函数。
  • 当第一个函数被调用时,我们定义了另一个函数。在示例中(id) => {}。这将采取我们的论点。
  • 第一个声明的(state) 部分。如果我们在不带参数的情况下采用常规 getter。我们始终可以访问 state 参数。 Vuex 为每个 getter 函数提供了这个。
  • 所以当我们调用以下代码时:store.getters.getTodoById(2)。你实际上是在做store.getters.getTodoById()(2)。在第一个函数调用中,您已经包含了状态。

所以,总结一下: 这个函数调用store.getters.getTodoById() 将返回一个函数。我们可以用我们的论点再次调用它。

根据链接示例将如下所示:

  getTodoById: function(state) {
    return function(id) {
      return state.todos.find(todo => todo.id === id);
    }
  }

【讨论】:

  • 非常感谢!我完全忘记了咖喱!
【解决方案2】:

这涉及到“函数的柯里化”,简单地说:

//①
const add = (x, y) => x + y;
add(2,3) // 5

这段代码的柯里化将是:

//②
const add = x => y => x + y;

把它变成 ES5 代码是这样的:

const add = function(x){

其中:

getters: {
    //...
    getTodoById: (state) => (id) => {
        return state.todos.find(todo => todo.id === id)
    }
}

可以写成它的等价物(就像②和①是等价的一样):

getters: {
    //...
    getTodoById: (state,id) => {
        return state.todos.find(todo => todo.id === id)
    }
}

state参数是getter的默认参数,可以这样调用:

store.getters.getTodoById(2);

参考:

https://stackoverflow.com/a/67221323/12261182

https://stackoverflow.com/a/32787782/11375753

【讨论】:

    猜你喜欢
    • 2021-04-14
    • 2021-07-06
    • 2017-06-29
    • 2021-03-28
    • 2017-10-01
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    相关资源
    最近更新 更多