2
头图

On the eve of 520 in 2021. In the past year, I have mainly been doing business, but I have never stopped pursuing and thinking about continuously improving the quality and speed of Coding. By coincidence, I was fortunate to spend time on perfecting a stable and easy-to-use state management program.

In the course of the author's work, he used redux at first, then vuex, then experimented with mobx, dva, react hooks and even self-developed tools, and finally returned to redux.

During this period, I have been exploring solutions that are simple to use and have complete type prompts. That is, when we enter one or two keywords, the IDE automatically pops up the model corresponding to the dispatch method, and then enters an empty string, and automatically prompts the method that may be called. To write too much state management code every day, there is no need to type a lot of repetitive content.

Then rewrite a state management library?

Redux is already very easy to use, but the code is slightly cumbersome, why do you need to rewrite it? Is it feasible to package based on redux?

Do you want to integrate other modules such as routing, modular loading, and network requests, so that users can do most things with this tool?

This is actually what many integrated frameworks do. But the state management itself is a single module, and there is no need to couple it with other modules. Modularization is far more convenient than integration for future partial upgrades and transformations of the project.

Now that we talked about type inference hints, is it only supported by the TypeScript project?

Of course, many types are defined with the help of TypeScript, but now using JSDoc comment type writing can also enable JS projects to support type hints and derivation.

Is it compatible with existing projects?

As long as the corresponding rules are followed, they are compatible under normal circumstances.

Program

The current state management scheme concept is:

  1. Use state model model manage state
  2. The state model contains the original state state and the updated state method methods
  3. All states and methods support type inference prompts

State model

The advantage of using the state model is that it can not only centrally manage the state, but also allow different components to share state across components.
At the same time, the common methods of each state model can be exposed in the model for external use.

The state model contains the original state state and the updated state method methods

To simplify the constituent elements of the model, only the state and the method of updating the state are required. The update state method is used to handle complex state updates, the so-called side effects.

{
    name: 'counter',
    state: {
        count: 0
    },
    methods: {
        add({ state, update }, number) {
            update({ count: state.count + number })
        }
        async delayAdd({ dispatch }, duration, number) {
            await new Promise(resolve => setTimeout( () => resolve(), duration ))
            dispatch('add', 1)
        }
        async run({ state, dispatch, getState }) {
            console.log('current count', state.count)
            await dispatch('delayAdd', 1000, 1)
            console.log('count after update', getState().count)
        }
    }
}

To directly update a certain state, you only need to expose a unique update method through the scheme library. such as:

updateModel('counter', { count: 100 })

All states and methods support type inference prompts

This is too important to greatly speed up the efficiency of research and development.

Code

Code implementation address:
Tredux: github.com/tredux-org/tredux

The project is just a reference. The most important thing is the concept of this state management scheme (the code level can be implemented in various ways).

In fact, the packaging is not difficult, the most difficult is how to make it cover the daily business development scenarios in the simplest usage.

If you think this solution is okay, and you want to use it in your own project or even your company's project, but don't worry about relying on external libraries, you can put the source code (a TS file) in the project for separate reference.

The existing scheme has been running steadily in the business project, and you are welcome to try it out.

end

Of course, this set of simple state management solution is just an introduction. It is also hoped that more lightweight and easy-to-use solutions will emerge on the market to make state management easier.

Thank you for taking the time to read this article. If you like this article, please like, bookmark and share it so that more people can see this article. This is also my greatest encouragement and support!

Welcome to subscribe to my blog via WeChat (search for "Suxiyun's blog" or scan the QR code below) or Github

微信公众号:苏溪云的博客


苏溪云
759 声望62 粉丝

5年前端, 分享最简单易懂技术文章