从React的背景开始,仅在定义了值的情况下才渲染视图。看起来像这样:
function Component ({ profile }) {
return (
<div>{profile && <div>{profile.name}}</div>
)
}
但是我发现很难在SwiftUI中复制这种模式。理想情况下,我们可以在视图中使用条件展开,但这当前不起作用。我唯一能找到的解决方案确实很精致:
struct ProfileView : View {
var profile: Profile?
var body : some View {
if let profile = profile {
return Text("profile: \(profile.bio)")
} else {
return Text("")
}
}
}
struct LayoutView : View {
@State var profile: Profile?
var body : some View {
Group {
ProfileView(profile: profile)
}
}.onAppear(perform: fetch)
// fetch method
}
有人使用可选值有更好的条件渲染策略吗?
答案 0 :(得分:2)
您可以使用map
来解决其他问题,例如:
struct ProfileView : View {
var profile: Profile?
var body : some View {
profile.map { Text("profile: \($0.bio)") }
}
}
({$0
是您在此示例中展开的profile
。)
如果需要其他情况:
profile.map { Text($0.bio) } ?? Text("Not available")
答案 1 :(得分:0)
只需执行以下操作:
struct LayoutView : View {
@State var profile: Profile?
var body : some View {
Group {
if profile != nil {
ProfileView(profile: profile!)
}
}
}.onAppear(perform: fetch)
// fetch method
}
答案 2 :(得分:0)
我会在子视图server{
listen 443 ssl http2 default_server;
ssl_certificate /etc/ssl/pse.crt;
ssl_certificate_key /etc/ssl/pse.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
auth_basic "Demo";
auth_basic_user_file conf/demo_passwd;
location / {
resolver 127.0.0.11; #docker dns
#workaround to defer resolving container name after it starts
set $target http://web:80;
proxy_pass $target;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
中使用@Binding
,以确保文本随着更改而与ProfileView
数据保持同步。这就是我要做的所有事情:
profile