首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Yew Framwork的Webassembly出现未捕获的错误

使用Yew Framwork的Webassembly出现未捕获的错误
EN

Stack Overflow用户
提问于 2020-10-28 19:15:48
回答 1查看 50关注 0票数 1

我正在使用Yew编写一个主题切换器,它通过单击在不同的主题之间循环。这是我的更新函数。它获取存储在共享状态中的当前主题,这取决于theme_cycle中接下来会发生什么。共享状态中的主题值将被设置为该主题。

代码语言:javascript
复制
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 == &current_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”,但是我的代码死机了,并且在浏览器控制台中得到了一个“未捕获的错误:未定义”。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-29 05:15:00

我找到了一种变通方法;我没有使用数组和访问值,而是尝试使用迭代器完成相同的任务,并确保update函数不拥有函数本身以外的任何变量(我不知道这是否真的有必要……)

代码语言:javascript
复制
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
}

如果有人知道我在第一次尝试中做错了什么,那就太酷了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64571703

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档