状态管理中的操作应该直接修改状态吗?

问题描述 投票:0回答:1

我正在使用 pinia 和 vue3,但这个问题适用于所有状态管理结构。

在操作中,我应该返回结果然后覆盖(或改变)状态还是直接修改状态作为副作用?

示例1:返回结果然后在组件处重新分配

const exampleStore = createStore({
  state: { someState: 1 },
  actions: {
    async getNewState() {
      const newState = await get();
      return newState;
    }
  }
});

//...then in some component in different file...
exampleStore.someState = await exampleStore.getNewState();

示例2:直接修改状态作为副作用

const exampleStore = createStore({
  state: { someState: 1 },
  actions: {
    async getNewState() {
      const newState = await get();
      this.someState = newState; // assign directly as a side-effect
    }
  }
});

虽然两种方法都很好,但我想知道哪种方法更值得推荐。

redux state vuex pinia
1个回答
0
投票

如果使用example1,则在组件中填写状态值。我通常使用example2,不需要在组件中填充状态值。但我添加了一个函数来重置状态值以返回初始值。

© www.soinside.com 2019 - 2024. All rights reserved.