我正在使用Yew编写一个主题切换器,它通过单击在不同的主题之间循环。这是我的更新函数。它获取存储在共享状态中的当前主题,这取决于theme_cycle中接下来会发生什么。共享状态中的主题值将被设置为该主题。
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::ChangeTheme => {
let theme_cycle: [&str; 3] = ["light", "dark", "rust"];
let current_theme = self.props.handle.state().theme.clone();
// eval next theme
let next_theme = match theme_cycle.iter().position(|x| x == ¤t_theme) {
None => theme_cycle[0].to_string(),
Some(i) => {
if i >= (current_theme.len() - 1) {
theme_cycle[0].to_string()
} else {
theme_cycle[i + 1].to_string()
}
},
};
// set next theme
self.props.handle.reduce(move |state| state.theme = next_theme.clone());
// store it inside localstorage
},
Msg::ToggleLangDropdown => self.show_dropdown = !self.show_dropdown,
};
true
}但是,如果共享状态中的主题val是"rust“,并且我再次单击调用Msg::ChangeTheme的按钮,则主题应该被设置为"light”,但是我的代码死机了,并且在浏览器控制台中得到了一个“未捕获的错误:未定义”。
发布于 2020-10-29 05:15:00
我找到了一种变通方法;我没有使用数组和访问值,而是尝试使用迭代器完成相同的任务,并确保update函数不拥有函数本身以外的任何变量(我不知道这是否真的有必要……)
fn update(&mut self, msg: Self::Message) -> ShouldRender {
match msg {
Msg::ChangeTheme => {
let theme_cycle = ["light".to_string(), "dark".to_string(), "rust".to_string()];
let current_theme = self.props.handle.state().theme.clone();
let indexof_current_theme = match theme_cycle.iter().position(|x| x.to_string() == current_theme) {
None => 0,
Some(x) => x.clone(),
};
let next_theme = match theme_cycle.iter().nth(indexof_current_theme + 1) {
None => theme_cycle.iter().nth(0).unwrap().clone(),
Some(x) => x.clone(),
};
self.props.handle.reduce(move |state| state.theme = next_theme.to_string());
},
Msg::ToggleLangDropdown => self.show_lang_dropdown = !self.show_lang_dropdown,
Msg::ToggleThemeDropdown => self.show_theme_dropdown = !self.show_theme_dropdown,
};
true
}如果有人知道我在第一次尝试中做错了什么,那就太酷了。
https://stackoverflow.com/questions/64571703
复制相似问题