简体   繁体   English

为什么我的数组在重建时填充但在页面刷新时不填充?

[英]Why Does My Array Populate on Rebuild But Not on Page Refresh?

I am using Vue 3 with Composition API, a Pinia store, TypeScript, SQL backend and Fetch to grab the data via my .NET 6 API. I am using Vue 3 with Composition API, a Pinia store, TypeScript, SQL backend and Fetch to grab the data via my .NET 6 API.

I have a User.ts class我有一个 User.ts class

export default class User
{
    userName: string | null
    
    constructor (userName: string | null)
    {
        this.userName = userName;
    }
}

and I Fetch the data from the DB using the below method我使用以下方法从数据库中获取数据

      getAdminUsers(): void
      {    
        fetch(apiURL + 'AdminUser',
        {
          headers:
          {
            "Accept": "application/json",
            "Content-Type": 'application/json'
          }
        })
        .then(response => 
          {
            return response.json();
          })
        .then(data =>
          { 
            this.$patch((state) =>
            {
              state.adminUser = { userName: null};
              state.adminUsers = [];
            })

            data.forEach((user: User) =>
            {
              if (user.userName)
              {
                this.adminUser = new User(user.userName.toUpperCase());
                this.adminUsers.push(this.adminUser);
              }
            })
          })
      },

For all the other data in my app, I have had no issues.对于我的应用程序中的所有其他数据,我没有遇到任何问题。 However, when I refresh the page, or try run the getAdminUsers method from anywhere in my Vue app, it returns an empty array.但是,当我刷新页面或尝试从 Vue 应用程序的任何位置运行 getAdminUsers 方法时,它会返回一个空数组。

[[Handler]]: Object
[[Target]]: Array(0)
length: 0
[[Prototype]]: Array(0)
[[IsRevoked]]: false

But when I make a tiny change to my app (such as add a space anywhere etc) and save>rebuild, the array is then populated with the correct data.但是当我对我的应用程序进行微小的更改(例如在任何地方添加空格等)并保存>重建时,数组就会填充正确的数据。

Proxy {0: User, 1: User}
[[Handler]]: Object
[[Target]]: Array(2)
0: User {userName: 'GEORGE.SMITHSON'}
1: User {userName: 'TEST.2'}
length: 2
[[Prototype]]: Array(0)
[[IsRevoked]]: false

I really don't understand why it is happening and can't get it to work correctly.我真的不明白它为什么会发生并且无法让它正常工作。 Any help is greatly appreciated!任何帮助是极大的赞赏!

Hard to say since you do not include how you're using the array.很难说,因为你不包括你如何使用数组。 It definitely sounds as if your array is not reactive for some reason.听起来你的数组由于某种原因没有反应。 That would explain why the array is not updating until a hot reload occurs.这可以解释为什么在热重载发生之前阵列不会更新。 Are you perhaps assigning it to another variable?您是否将其分配给另一个变量? Is that variable also reactive?该变量是否也是反应性的? If you are assigning it should be something like this:如果你要分配它应该是这样的:

const adminStore = useAdminStore();
const adminUsers = computed(() => adminStore.adminUsers);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM