Add memochain example

This commit is contained in:
Jonathan Kelley committed 2024-01-26 22:33:41 -08:00
1 parent b3f018f805
commit d34538f4da
3 files changed
+55 -3

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
use dioxus::prelude::*;
fn main() {
launch_desktop(app);
}
fn app() -> Element {
let mut state = use_signal(|| 0);
let mut depth = use_signal(|| 1 as usize);
let mut items = use_memo(move || (0..depth()).map(|f| f as _).collect::<Vec<isize>>());
let a = use_memo(move || state() + 1);
println!("rendering app");
rsx! {
button { onclick: move |_| state += 1, "Increment" }
button { onclick: move |_| depth += 1, "Add depth" }
button { onclick: move |_| depth -= 1, "Remove depth" }
Child {
depth: depth.into(),
items: items,
state: a,
}
}
}
#[component]
fn Child(
state: ReadOnlySignal<isize>,
items: ReadOnlySignal<Vec<isize>>,
depth: ReadOnlySignal<usize>,
) -> Element {
if depth() == 0 {
return None;
}
println!("rendering child: {}", depth());
let state = use_memo(move || state() + 1);
let item = use_memo(move || items()[dbg!(depth()) - 1]);
let depth = use_memo(move || depth() - 1);
rsx! {
h3 { "Depth({depth})-Item({item}): {state}"}
Child {
depth,
state,
items
}
}
}
+2 -2
View File
@@ -39,7 +39,7 @@ fn app() -> Element {
button { onclick: move |_| count -= 1, "Down low!" }
button { onclick: move |_| running.toggle(), "Toggle counter" }
button { onclick: move |_| saved_values.push(count().to_string()), "Save this value" }
button { onclick: move |_| saved_values.write().clear(), "Clear saved values" }
button { onclick: move |_| saved_values.clear(), "Clear saved values" }
// We can do boolean operations on the current signal value
if count() > 5 {
@@ -47,7 +47,7 @@ fn app() -> Element {
}
// We can cleanly map signals with iterators
for value in saved_values.read().iter() {
for value in saved_values.iter() {
h3 { "Saved value: {value}" }
}