(1) define and share module status

Time:2021-2-13

(1) define and share module status

Open source is not easy. Thank you for your support, ❤ star concent^_^

preface

[instant]It’s a quick way to help beginners get startedconcentTo learn and understand the concept of center state management.

Although I have learned and used itreduxandmboxThis article will be easier to understand, but users who have not used any state management libraries can also get started quicklyconcent, real0 barriersLearn to use it and connect to your react application.

Notice the emphasis0 barriers, including learning to use and accessing applications. In order to achieve this goal, the API should be simple enough. How simple is it? It’s too simple to add, too simple to sum upreactKeep 100% consistency, so that novices can access state management in the way of react component writing without understanding additional overview, but also retain a higher-level abstract interface, so that veteran can follow thereduxTo organize code.

Come on, show! The key APIs covered in this issue include three top-level APIsrunuseConcentregister, an instance context APIsetStateLearn to use these four APIs, and you will already use center as your state management solution.

Hello world

All the frameworks will be based onHello worldAs a guide, we are no exception here. Let’s have a lookconcentVersion ofHello worldHow simple it is.

Run definition module

Like Redux, center has a single global state tree, which is a common JSON object. However, the first level key is planned as the module name to help users divide the state into multiple modules according to the business scenario, which is convenient for separate management.

Here we need to userunInterface to start the center and load the module configuration. Configure ahelloAnd define the state for it

import { run } from 'concent';

run({
  hello: {
    state: { greeting: 'Hello world' },
  },
});

Register class component

After the module is defined, our components need to consume the status of the module. For class components, useregisterthat will do

import { register } from 'concent';

@register('hello')
class HelloCls extends React.Component{
  state = { greeting: '' };
  changeGreeting = (e)=> this.setState({greeting: e.target.value})
  render(){
    return <input value={this.state.greeting} onChange={this.changeGreeting} />
  }
}

For appeal coderegisterThe interface willHelloClsComponent registration belongs tohelloModule, the center will send thethisAn instance context is injected into thectx, which is used to read data and call modification methods. It also silently replaces thestateandsetStateIt is convenient for users to change the code of the original component by 0registerYou can access state management by decorating class components. This is0 barriersLearn to use and access to the foundation of react application. For beginners, if you can write react components, you will already use center without any extra learning cost.

this.state === this.ctx.state; // true
this.setState === this.ctx.setState; // true

In the above code, a class member variable is also declaredstatebe equal to{ greeting: '' }BecausegreetingAnd module state, so its value will be replaced by module state before the first renderingHello worldIn fact, this class member variable can not be declared herestateWrite it just to make sure you delete itregisterThe decorator component also works without getting oneundefinedOfgreetingInitial value.

Useconcent registration function component

useuseConcentInterface registers the module of the current component,useConcentReturns the instance context object of the current componentctx, which is equivalent to thethis.ctxWe just need to deconstruct itstateandsetStateThat’s it.

import { useConcent } from 'concent';

function HelloFn(){
  const { state, setState } = useConcent('hello');
  const changeGreeting = (e)=> setState({greeting: e.target.value})
  return <input value={state.greeting} onChange={changeGreeting} />
}

Rendering Components

Finally, let’s take a look at the complete code, and we find that there is no top-level codeProviderThe root component is wrapped by a component such asReact Context apiTo achieve state management, you maintain an independent global context, so it’s very easy for you to access the center in existing projects, plug and play, without any additional modification.

becauseHelloClsandHelloFnComponents belong tohelloModule, any one of them will modify the module state, and the center will store it in the store and synchronize it with other instances that belong to the same modulehelloOn the instance of module, state sharing is so simple.

import ReactDOM from 'react-dom';
import { run } from 'concent';
import { register, useConcent } from 'concent';

Run ({/ * * /});

@register('hello')
class HelloCls extends  React.Component {/ * * /}

Function hellofn() {/ * * /}

const App = ()=>(
  <div>
     <HelloCls />
     <HelloFn />
  </div>
);

ReactDOM.render(App, document.getElementById('root'));

Click me to check the source code

Dependent collection

Whether it’s a class component or a function component, you canstateObject has been converted to aProxyProxy object is responsible for collecting the data dependency of the current rendering, so if the read state is conditional judgment, it is recommended to use the delayed deconstruction writing method, so that each rendering can lock the minimum dependency list, reduce redundant rendering, and obtain better performance.

function HelloFn(){
  const { state, setState, syncBool } = useConcent({module:'hello', state:{show:true}});
  const changeGreeting = (e)=> setState({greeting: e.target.value});
  //When show is true, the dependency of the current instance is ['meeting ']. If the meeting value is changed anywhere else, the current instance will be re rendered
  //When show is false, the current instance has no dependency. Changing the greeting value anywhere else will not affect the re rendering of the current instance
  return (
      <>
    {state.show?<input value={state.greeting} onChange={changeGreeting} />:'no input'}
    <button onClick={syncBool('show')}>toggle show</button>
    </>
  );
}

Consuming module states across multiple modules

When a component needs to consume data from multiple modules, it can use theconnectParameter to declare multiple modules to be connected.

Use the connect parameter to connect multiple modules

As shown in the following example, the bar and Baz modules are connected through thectx.connectedStateGet target module status:

@register({connect:['bar', 'baz']})
class extends React.Component{
  render(){
    const { bar, baz } = this.ctx.connectedState;
  }
}

fromconnectedStateThe obtained module state still has dependency collection behavior, so if there are conditional rendering statements, the delayed deconstruction writing method is recommended

Using setmodulestate to modify the state

By calling instance context APIctx.setModuleStateModify target module status

changeName = e=> this.ctx.setModuleState('bar', {name: e.target.value})

epilogue

This article only demonstrates the most basic API usage, to help you quickly start concent, if you are an old driver, especiallyvue3 one pieceAt this juncture when the official release has been announced, if you are very dismissive of such clumsy code organization, don’t rush to deny it for the moment, and open the official website to have a look at other features, there must be highlights you like, including the composition API tailored for react, module levelreducercomputedwatchlifecycleAnd other new features will be mentioned one by one later.

Center carries a complete set of solutions to supportProgressiveThe development of react components does not interfere with the development philosophy and component form of react itself, but also can obtain huge performance benefits, which means that we can gradually outline and separate the incremental iteration from the bottom up, the division of state modules, the management of derived data, the classification of event models, and the separation of business codes in the development process, and the process is smooth Flexible, but also allows us to top-down co-ordinated development, at the beginning of all the domain model and business module Abstract clear, at the same time in the iterative process can also be very fast flexible adjustment and affect the entire project architecture

Recommended Today

Deeply analyze the principle and practice of RSA key

1、 Preface After experiencing many dark moments in life, when you read this article, you will regret and even be angry: why didn’t you write this article earlier?! Your darkest moments include: 1. Your project needs to be connected with the bank, and the other party needs you to provide an encryption certificate. You have […]