简体   繁体   English

SwiftUI 状态变量未更新

[英]SwiftUI State Variable Not Updating

I have a struct User with a list of hobbies as follows:我有一个 struct User ,其中包含一个爱好列表,如下所示:

struct User: Hashable, Codable, Identifiable, Equatable {
    var id: String
    var name: String
    var hobbies: [String]
}

I then generate a list view using a list of users as a state variable.然后我使用用户列表作为状态变量生成一个列表视图。 When the button in the list view is clicked a new hobby is added to a user's hobbies.当单击列表视图中的按钮时,一个新的爱好被添加到用户的爱好中。

struct UsersListView: View {

    @State var users: [User]


    var body: some View {

                TitleView(titleText: "Friends")
                    .padding(.leading, 30.0)

                List(userDisplayList) { user in
                     Text(user.name)
                     Text(user.hobbies.joined(separator: ", "))
                     Button(action: {self.users[0].hobbies.append("new hobby")}
                }
            }
        }
    }
}

However, when I click on the button, the users state variable does not change and remains the same.但是,当我单击按钮时,用户状态变量不会更改并保持不变。 Can anyone explain what is going on here?谁能解释这里发生了什么?

You display every user in userDisplayList , not in users .您在userDisplayList显示每个用户,而不是在users

So when you change some value in users , SwiftUI think that there is nothing to update in your view, since nothing depends on users variable.因此,当您更改users某些值时,SwiftUI 认为您的视图中没有任何可更新的内容,因为没有任何内容取决于users变量。

Try using List(users) { user in instead if there is no additional logic in your userDisplayList .如果您的userDisplayList没有其他逻辑,请尝试使用List(users) { user in

Try this:尝试这个:

    struct User: Hashable, Codable, Identifiable, Equatable {
    var id = UUID()
    var name: String
    var hobbies: [String]
}

struct UsersListView: View {

    @State var users: [User] = [User(name: "aaaa", hobbies: [])]


    var body: some View {

        List(users) { user in
                     Text(user.name)
                     Text(user.hobbies.joined(separator: ", "))
                        Button(action: {
                            self.users[0].hobbies.append("new hobby")
                        }) {
                            Text("Create hobby")
                        }

                }
            }
        }

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

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