reducer.rs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //! Example: Reducer Pattern
  2. //! -----------------
  3. //! This example shows how to encapsulate sate in dioxus components with the reducer pattern.
  4. //! This pattern is very useful when a single component can handle many types of input that can
  5. //! be represented by an enum.
  6. use dioxus::prelude::*;
  7. fn main() {
  8. dioxus::desktop::launch(App, |c| c);
  9. }
  10. pub static App: FC<()> = |cx| {
  11. let (state, reduce) = use_reducer(cx, PlayerState::new, PlayerState::reduce);
  12. let is_playing = state.is_playing();
  13. cx.render(rsx! {
  14. div {
  15. h1 {"Select an option"}
  16. h3 {"The radio is... {is_playing}!"}
  17. button {
  18. "Pause"
  19. onclick: move |_| reduce(PlayerAction::Pause)
  20. }
  21. button {
  22. "Play"
  23. onclick: move |_| reduce(PlayerAction::Play)
  24. }
  25. }
  26. })
  27. };
  28. enum PlayerAction {
  29. Pause,
  30. Play,
  31. }
  32. struct PlayerState {
  33. is_playing: bool,
  34. }
  35. impl PlayerState {
  36. fn new() -> Self {
  37. Self { is_playing: false }
  38. }
  39. fn reduce(&mut self, action: PlayerAction) {
  40. match action {
  41. PlayerAction::Pause => self.is_playing = false,
  42. PlayerAction::Play => self.is_playing = true,
  43. }
  44. }
  45. fn is_playing(&self) -> &'static str {
  46. match self.is_playing {
  47. true => "currently playing!",
  48. false => "not currently playing",
  49. }
  50. }
  51. }