更好的方式是在操作中还是在组件内部突变Pinia状态?

huangapple go评论49阅读模式
英文:

Is better mutate Pinia state inside actions or inside component?

问题

我在我的Pinia store中有这个函数:

async function getCurrentUser(){
    let user: User | undefined = undefined;
    if (auth.currentUser?.uid) {
      user = await getUserById(auth.currentUser.uid)
      state.value.currentUser = user;
    }
  }

所以,在组件中,我只需要调用:
userStore.getCurrentUser();
然后我就可以从状态中访问当前用户:
userStore.state.currentUser
但是这种方法让我感到困惑,因为我们在获取函数内部改变了状态。

因此,我认为这种方法更好(在组件内部):

userStore.state.currentUser = await getUserById(auth.currentUser.uid)
userStore.state.currentUser //做你想做的事情

哪种选项更好?我不能决定。

这个问题更多地涉及方法而不是特定实现(以getCurrentUser函数的形式)。

英文:

I have this function in my Pinia store:

async function getCurrentUser(){
    let user: User | undefined = undefined;
    if (auth.currentUser?.uid) {
      user = await getUserById(auth.currentUser.uid)
      state.value.currentUser = user;
    }
  }

So, inside a component I just need to call:
userStore.getCurrentUser();
And I will get access to the current user from the state:
userStore.state.currentUser
But this approach confuses me, because we are mutating the state inside the get function.

Therefore, I think it would be better to do this (inside a component):

userStore.state.currentUser = await getUserById(auth.currentUser.uid)
userStore.state.currentUser //Do whatever you want

Which option is better? I can't make up my mind.

This question is more about the approach rather than the specific implementation (in the form of the getCurrentUser function)

答案1

得分: 0

我认为将该函数重命名为setCurrentUser()而不是getCurrentUser()会更合适,以使其目的更清晰,避免混淆。通过使用set后跟状态属性的命名约定,它表明该函数负责更新Pinia存储中的currentUser状态。

在Pinia中,通常提供了用于读取和更新状态的单独函数。存储库公开了状态对象,以便组件可以读取它们,允许它们使用userStore.state.currentUser来访问当前用户。要更新状态,组件可以调用存储库中的setCurrentUser()函数。

英文:

I think it would be more appropriate to rename the function to setCurrentUser() rather than getCurrentUser() to make its purpose clearer and avoid confusion. By using the naming convention of set followed by the name of the state property, it indicates that the function is responsible for updating the currentUser state in the Pinia store.

In Pinia, it is common to provide separate functions for reading and updating the state. The store exposes the state object for components to read, allowing them to access the current user using userStore.state.currentUser. To update the state, components can call the setCurrentUser() function in the store

huangapple
  • 本文由 发表于 2023年6月29日 12:34:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定