乐闻世界logo
搜索文章和话题

Yew 组件生命周期包含哪些方法,每个方法的作用是什么?

2月19日 16:22

Yew 组件生命周期详解

Yew 组件的生命周期与 React 类似,但使用 Rust 的 trait 系统来实现。理解组件生命周期对于构建高效的应用至关重要。

主要生命周期方法

1. create()

  • 时机:组件首次创建时调用
  • 用途:初始化组件状态
  • 返回值:返回组件的初始状态
  • 示例
rust
impl Component for MyComponent { type Message = Msg; type Properties = Props; fn create(ctx: &Context<Self>) -> Self { Self { counter: 0, value: String::new(), } } }

2. view()

  • 时机:每次状态或属性变化时调用
  • 用途:渲染组件的 UI
  • 返回值:返回 Html 类型
  • 示例
rust
fn view(&self, ctx: &Context<Self>) -> Html { html! { <div class="container"> <h1>{ "Counter: " }{ self.counter }</h1> <button onclick={ctx.link().callback(|_| Msg::Increment)}> { "Increment" } </button> </div> } }

3. update()

  • 时机:接收到消息时调用
  • 用途:处理状态更新
  • 返回值:返回 bool,表示是否需要重新渲染
  • 示例
rust
fn update(&mut self, ctx: &Context<Self>, msg: Self::Message) -> bool { match msg { Msg::Increment => { self.counter += 1; true // 需要重新渲染 } Msg::NoOp => false, // 不需要重新渲染 } }

4. changed()

  • 时机:组件的 props 发生变化时调用
  • 用途:决定是否根据新的 props 更新组件
  • 返回值:返回 bool,表示是否需要重新渲染
  • 示例
rust
fn changed(&mut self, ctx: &Context<Self>, _old_props: &Self::Properties) -> bool { // 只有当重要属性变化时才重新渲染 true }

5. rendered()

  • 时机:组件渲染到 DOM 后调用
  • 用途:执行 DOM 操作、初始化第三方库等
  • 示例
rust
fn rendered(&mut self, ctx: &Context<Self>, first_render: bool) { if first_render { // 首次渲染后的初始化操作 } }

6. destroy()

  • 时机:组件从 DOM 中移除时调用
  • 用途:清理资源、取消订阅等
  • 示例
rust
fn destroy(&mut self, ctx: &Context<Self>) { // 清理定时器、取消网络请求等 } }

生命周期流程图

shell
创建组件 create() → 初始化状态 view() → 渲染 UI rendered() → DOM 操作 [接收消息/props 变化] update() / changed() → 更新状态 view() → 重新渲染 rendered() → DOM 更新 [组件卸载] destroy() → 清理资源

最佳实践

  1. 避免在 view() 中执行复杂计算:将计算逻辑放在 update() 或单独的方法中
  2. 合理使用 changed():避免不必要的重新渲染
  3. 及时清理资源:在 destroy() 中清理定时器、事件监听器等
  4. 使用 rendered() 处理 DOM 操作:确保 DOM 已经渲染完成
标签:Yew