فهرست منبع

feat: add some helpers to use_ref

Jonathan Kelley 3 سال پیش
والد
کامیت
45473ece8c
2فایلهای تغییر یافته به همراه32 افزوده شده و 0 حذف شده
  1. 21 0
      examples/use_ref.rs
  2. 11 0
      packages/hooks/src/useref.rs

+ 21 - 0
examples/use_ref.rs

@@ -0,0 +1,21 @@
+use std::collections::HashMap;
+
+use dioxus::prelude::*;
+fn main() {}
+
+fn app(cx: Scope) -> Element {
+    let val = use_ref(&cx, || HashMap::<u32, String>::new());
+
+    // Pull the value out locally
+    let p = val.read();
+
+    // to get an &HashMap we have to "reborrow" through the RefCell
+    // Be careful: passing this into children might cause a double borrow of the RefCell and a panic
+    let g = &*p;
+
+    cx.render(rsx! {
+        div {
+            "hi"
+        }
+    })
+}

+ 11 - 0
packages/hooks/src/useref.rs

@@ -42,6 +42,17 @@ impl<T> UseRef<T> {
         self.value.borrow_mut()
     }
 
+    /// Take a reference to the inner value termporarily and produce a new value
+    pub fn with<O>(&self, f: impl FnOnce(&T) -> O) -> O {
+        f(&*self.read())
+    }
+
+    /// Take a reference to the inner value termporarily and produce a new value,
+    /// modifying the original in place.
+    pub fn with_mut<O>(&self, f: impl FnOnce(&mut T) -> O) -> O {
+        f(&mut *self.write())
+    }
+
     pub fn needs_update(&self) {
         (self.update_callback)();
     }