首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Yew中使用wasm_timer重复执行回调

在Yew中使用wasm_timer重复执行回调
EN

Stack Overflow用户
提问于 2022-02-25 18:39:31
回答 1查看 340关注 0票数 1

我对锈病还是很陌生的,很难为未来做好准备。我想在浏览器中实现一个“计时器应用程序”,并使用https://yew.rs/。对于计时器,我尝试使用https://github.com/tomaka/wasm-timer/,但是没有文档,也没有示例。看起来这个用法应该是显而易见的,但我不明白。

我想我得做这样的事:

代码语言:javascript
复制
let i = Interval::new(core::time::Duration::from_millis(250));

这应该会产生一个间隔,每250毫秒触发一次。但什么被解雇了?如何指定我的回调?我希望这样的事情:

代码语言:javascript
复制
i.somehow_specify_callback(|| { ... executed every 250ms ...});

我的感觉是,不知何故,我走错了路,没有把握铁锈的未来。非常希望提供一个关于如何使Interval执行某些代码的工作示例。

EN

回答 1

Stack Overflow用户

发布于 2022-03-25 10:53:38

下面是计时器组件的伪代码示例:

代码语言:javascript
复制
enum SecondsStateAction {
    Increment,
}

#[derive(Default)]
struct SecondsState {
    seconds: usize,
}

impl Reducible for SecondsState {
    /// Reducer Action Type
    type Action = SecondsStateAction;

    /// Reducer Function
    fn reduce(self: Rc<Self>, action: Self::Action) -> Rc<Self> {
        match action {
            SecondsStateAction::Increment => Self { seconds: self.seconds + 1 }.into(),
        }
    }
}

#[function_component(Timer)]
pub fn timer() -> Html {
    let seconds_state_handle = use_reducer(SecondsState::default);

    use_effect_with_deps(
        {
            let seconds_state_handle = seconds_state_handle.clone();

            move |_| {
                // i intervals get out of scope they get dropped and destroyed
                let interval = Interval::new(1000, move || seconds_state_handle.dispatch(SecondsStateAction::Increment));

                // So we move it into the clean up function, rust will consider this still being used and wont drop it
                // then we just drop it ourselves in the cleanup 
                move || drop(interval)
            }
        },
        (), // Only create the interval once per your component existence
    );

    html! {<h1>{*seconds_state_handle}{" seconds has passed since this component got rendered"}</h1>}
}

要了解关于代码中使用的钩子的更多信息,请访问https://yew.rs/docs/concepts/function-components/pre-defined-hooks

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

https://stackoverflow.com/questions/71270366

复制
相关文章

相似问题

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