Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement event-driven state management in React

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to implement event-driven state management in React". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to do event-driven state management in React.

Store

A store is a collection of data stored in the application state. It is created through the createStoreon () function imported from the Storeon library.

The createStoreon () function accepts a list of modules, where each module is a function that accepts store parameters and binds its event listeners. This is an example of store:

Import {createStoreon} from 'storeon/react' / / todos module const todos = store = > {store.on (event, callback)} export default const store = createStoreon ([todos]) modularization

Store in Storeon is modular, that is, they are defined independently and are not bound to Hook or components. Each state and its operation are defined in a function called a module. These modules are passed to the createStoreon () function and registered as a global store.

There are three ways to store:

Store.get ()-used to retrieve the current data in the state.

Store.on (event, callback)-used to register the event listener with the specified event name.

Store.dispatch (event, data)-used to emit events and pass in optional data based on defined event requirements.

Events

Storeon is an event-based state management library, and state changes are made by events defined in the state module. There are three built-in events in Storeon that start with @. Other events are not defined with the @ prefix. The three built-in events are

@ init-this event is triggered when the application is loaded. It is used to set the initial state of the application and execute everything in the callback passed to it.

@ dispatch-this event is triggered on each new action. This is useful for debugging.

@ changed-this event is triggered when the application state changes.

Note: store.on (event,callback) is used to add event listeners to our module.

Demo program

To demonstrate how to perform application state operations in Storeon, we will build a simple notes program. You will also use another software package from Storeon to save the state data in localStorage.

Suppose you have basic knowledge of JavaScript and React. You can find the code used in this article on https://github.com/Youngestdev/storeon-app.

Set up

Before going any further, let's outline the project structure and the installation of dependencies required by the Notes program. Start by creating a project folder.

Mkdir storeon-app & & cd storeon-app mkdir {src,public,src/Components} touch public/ {index.html, style.css} & & touch src/ {index,store,Components/Notes} .js

Next, initialize the directory and install the required dependencies.

Npm init-y npm i react react-dom react-scripts storeon @ storeon/localstorage uuidv4

The next step is to write the parent component in the index.js file.

`index.js`

This file is responsible for rendering our note component. First import the required package.

Import React from 'react' import {render} from' react-dom'; function App () {return (Hello!);} const root = document.getElementById ('root'); render (, root)

Next, you build the store by writing code in store.js for initialization and manipulation of the state.

`store.js`

This file is responsible for handling the status in the application and subsequent state management operations. We must create a module to store state and support events to handle operational changes.

First, import the createStoreon method and the unique random ID generator UUID from Storeon.

The createStoreon method is responsible for registering our state with the global store.

Import {createStoreon} from 'storeon'; import {v4 as uuidv4} from' uuid' import {persistState} from'@ storeon/localstorage'; let note = store = > {}

We store the state in the array variable notes, which contains comments in the following format:

{id: 'note id', item:' note item'}

Next, we will initialize the state with two comments (which will be displayed when the program is started for the first time), thus populating the comment module first. Then, define the status event.

Let note = store = > {store.on ('@ init', ()) > ({notes: [{id: uuidv4 (), item: 'Storeon is a React state management library and unlike other state management libraries that use Context, it utilizes an event-driven approach like Redux.'}, {id: uuidv4 (), item:' This is a really short note. I have begun to study the basic concepts of technical writing and I'\'m optimistic about becoming one of the best technical writers.'},]}); store.on ('addNote', ({notes}, note) = > {return {notes: [... notes, {id: uuidv4 (), item: note}],}}); store.on (' deleteNote', ({notes}, id) = > ({}); 16})

In the above code, we define the state and populate it with two short comments, and define two events and a callback function that will be executed after an event is issued from the dispatch (event, data) function.

In the addNote event, we return the updated state object with the new note added, and filter out the note that passes the ID to the scheduling method in the deleteNote event.

Finally, assign the module to the exportable variable store and register it as a global store so that it can be imported into the context provider later and the state is stored in the localStorage.

Const store = createStoreon ([notes, / / Store state in localStorage persistState (['notes']),]); export default store

Next, write the Notes application component in Notes.js.

`Notes.js`

This file contains the components of the Notes program. We will start by importing dependencies.

Import React from 'react'; import {useStoreon} from' storeon/react'

Next, write the component.

Const Notes = () = > {const {dispatch, notes} = useStoreon ('notes'); const [value, setValue] = React.useState ('');}

In the second line of the code above, the return value of useStoreon () hook is set to a breakable object. UseStoreon () hook takes the module name as its parameter and returns the status and scheduling method to emit events.

Next, define the way to emit state definition events in the component.

Const Notes = () = > {. Const deleteNote = id = > {dispatch ('deleteNote', id)}; const submit = () = > {dispatch (' addNote', value); setValue ('');}; const handleInput = e = > {setValue (e.target.value);};}

Let's review the three methods defined above:

DeleteNote (id)-this method dispatches deleteNote events when triggered.

Submit ()-this method dispatches the addNote event by passing the value of the input state, which is defined locally in the Notes component.

HandleInput ()-this method sets the value of the local state to user input.

Next, we'll build the main interface of our app and export it. Next, we will build the main interface of the application and export it.

Const Notes = () = > {. Return (Quick Notes submit ()} > Add A Note {notes.map (note = >)

{note.item}

DeleteNote (note.id)} > Delete note)})); 24} 25

This makes up our Notes component. Next, write a stylesheet for our application and index.html file.

`index.html` Storeon Todo App

Next, populate the style.css file.

`style.css` * {box-sizing: border-box; margin: 0; padding: 0;} section {display: flex; justify-content: center; align-items: center; flex-direction: column; width: 300px; margin: auto;} header {text-align: center; font-size: 24px; line-height: 40px;} ul {display: block;}. Todo {display: block; margin: 12px 0; width: 300px; padding: 16px Box-shadow: 0 8px 12px 0 rgba (0,0,0,0.3); transition: 0.2s; word-break: break-word;} li {list-style-type: none; display: block;} textarea {border: 1px double; box-shadow: 1px 1px 1px # 999; height: 100px; margin: 12px 0; width: 100%; padding: 5px 10px;} button {margin: 8px 0; border-radius: 5px; padding: 10px 25px }. Box:hover {box-shadow: 0 8px 16px 0 rgba (0,0,0,0.2);} run

Now we have successfully written the components and stylesheets, but we have not updated the parent component in index.js to render the Notes component. Next let's render the Notes component.

`index.js`

To access our global store, we must import the store and Storeon store context components. We will also import the notes component for rendering.

Replace the contents of the component with the following code:

Import {render} from 'react-dom'; import {StoreContext} from' storeon/react'; import Notes from'. / Components/Notes'; import store from'. / src/store'; function App () {return ();} const root = document.getElementById ('root'); render (, root)

On lines 8-10, the store context provider component is invoked and the notes component is passed as a consumer. The store context provider component has the global store as its context value.

Next, edit the script section of the package.json file to the following:

"scripts": {"start": "react-scripts start",}

Then run our program:

Npm run start

Let's continue to add and remove comments:

Storeon devtools

Storeon has similar properties to Redux and allows you to visualize and monitor state changes in Redux DevTools. To visualize the state in the Storeon program, we will import the devtools package and add it as a parameter to the createStoreon () method of our store.js file.

... Import {storeonDevtools} from 'storeon/devtools';... const store = createStoreon ([..., process.env.NODE_ENV! = =' production' & & storeonDevtools,])

This is a demonstration of visualizing state changes with Redux DevTools:

At this point, I believe you have a deeper understanding of "how to do event-driven state management in React". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report