【问题标题】:Dispatch receiving undefined as a value调度接收未定义为值
【发布时间】:2018-11-14 13:56:48
【问题描述】:

我在调度后更新状态时遇到问题。

控制台记录 dispatch 的结果显示 Promise pending 和值 undefined 因此,永远不会到达商店。

console result

下面是调用dispatch处理程序的函数。

unsetSelected() {
   let some = this.$store.dispatch('user/selectedDevice', null)
   console.log(some)
}


<span class="ellipsis" @click="setSelected(device)">
     <i v-if="selectedDevice && selectedDevice.id == device.id"
        @click="unsetSelected()"
        class="fa fa-times-circle">
     </i>
     <i v-else="" class="fa fa-ellipsis-v"></i>
</span>

这是动作处理程序:

selectedDevice ({ commit }, data) {
    commit ('SELECTED_DEVICE', data);
}

【问题讨论】:

    标签: vue.js vuex nuxt.js


    【解决方案1】:

    我在突变处理程序上发出警报,发现代码按预期工作,只是它还在 DOM 中触发了上面的 dispatch 函数。

    我必须用.stop修饰符链接它:@click.stop="unsetSelected()"

    【讨论】:

      【解决方案2】:

      来自dispatch 实例方法的 Vuex API 参考:

      返回解析所有触发的操作处理程序的 Promise。

      所以调用dispatch 会返回Promise。为了在组件内部接收数据,这个 promise 应该被解析。

      你可以修改组件的方法如下:

      // using async/await
      async unsetSelected() {
        try {
          let some = await this.$store.dispatch('user/selectedDevice', null)
          console.log(some)
        } catch (error) {
          // handle error
        }
      }
      
      // using Promise API
      unsetSelected() {
        this.$store.dispatch('user/selectedDevice', null)
          .then((some) => {
            console.log(some)
          })
          .catch((error) => {
            // handle error
          })
      }
      

      此外,selectedDevice 不返回任何数据,因此来自已解决承诺的 some(或响应)将是 undefined,例如有问题的代码。

      要解决这个问题,存储操作应该有一个 return 语句,其中包含要返回到组件的所需数据。

      不过,按照 Vuex 架构,建议map state/getters,其值将在状态突变提交后响应更新。

      【讨论】:

      • 所有你建议我已经完成但仍然返回未定义。我为selectedDevice 设置了吸气剂,但仍然无法正常工作。 @aBiscuit
      • 您是否能够解决 Promise,但它仍然显示 undefined?您期望在哪里获得价值?
      • 我想在商店里收到export const state = () =&gt;({ devices: null, selectedDevice: null }) 然后通过computed 属性将它放入组件中
      • computed: { selectedDevice() { return this.$store.getters['user/selectedDevice'] } }
      • 请在问题中添加SELECTED_DEVICE 变异代码,以验证所有内容都在更新。
      猜你喜欢
      • 1970-01-01
      • 2017-01-17
      • 2017-05-21
      • 1970-01-01
      • 2021-09-09
      • 2021-11-12
      • 2020-10-01
      • 1970-01-01
      • 2022-11-02
      相关资源
      最近更新 更多