英文:
How to get the value from state in Yew Rust
问题
我在 Yew 中有一个状态,看起来像这样:
let is_flipped: UseStateHandle<bool> = use_state(|| false);
如你所见,它的类型是 `UseStateHandle<bool>`。
我想要提取其中的布尔值,以便可以切换状态:
let onclick: Callback<MouseEvent> = {
let is_flipped = is_flipped.clone();
Callback::from(move |_| match is_flipped {
true => is_flipped.set(false), // <- 类型错误
false => is_flipped.set(true), // <- 类型错误
})
};
但是我得到了这个错误:
^^^^^ 期望结构体 UseStateHandle
,找到 bool
我怎样才能获得状态中包含的布尔值呢?
英文:
I have a state in Yew that looks like this:
let is_flipped: UseStateHandle<bool> = use_state(|| false);
As you can see, its type is UseStateHandle<bool>
.
I want to extract its boolean value so I can toggle the state:
let onclick: Callback<MouseEvent> = {
let is_flipped = is_flipped.clone();
Callback::from(move |_| match is_flipped {
true => is_flipped.set(false), // <- type error
false => is_flipped.set(true), // <- type error
})
};
But I am getting this error:
^^^^^ expected struct `UseStateHandle`, found `bool`
How can I obtain the boolean value contained in the state?
答案1
得分: 4
UseStateHandle
实现了Deref
。你只需要对它进行解引用:
let onclick: Callback<MouseEvent> = {
let is_flipped = is_flipped.clone();
Callback::from(move |_| match *is_flipped {
true => is_flipped.set(false),
false => is_flipped.set(true),
})
};
英文:
UseStateHandle
implements Deref
. You just need to dereference it:
let onclick: Callback<MouseEvent> = {
let is_flipped = is_flipped.clone();
Callback::from(move |_| match *is_flipped {
true => is_flipped.set(false),
false => is_flipped.set(true),
})
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论