preface

Some time ago, we needed to encapsulate a classv-modelReactComponent. This component needs to be passedfieldField that requires the string path of the value passed in. At this point, wheninputIs synchronized to modify the data sourcename; When modifying the data sourcenameValue is synchronized toinputComponents. Due to thedivThere may be component nesting within, so use itContext. (PS: Because of the extracted component, both want it to support the new versionContext, also want it to support the older versionContextFor this reason.)

How do I integrate old and new contexts

It is not just possible to pass data across componentsContextYou can do it byEvent subscriptionTo implement.mini-create-react-contextInside is emulation using the event subscription modelcreateContext, probably most people are unfamiliar with this three-way package, but everyone isreact-routerDefinitely not unfamiliar,react-routerThe internal source code is created using this tripartite packageContext.mini-create-react-contextInternal will not exist in the new versionContextWhen exposed to the outside worldcreateReactContextMethod, which receivesdefaultValueAnd returnProviderConsumerTwo components. We see firstProviderComponents, components will pass through the old versionContextPass an event subscriber to the descendant whenever the component’spropsEvents are pushed through the event subscriber when changes occur. ConsumerComponents in thecomponentDidMountSubscribes to events through the event subscriber passed in, and passes if the event is receivedonUpdateMethod to executesetState, update the component.At this point, I have to mention the old versionContextThe old editionContextIf in the middle of data transmission componentsSCUreturnfalse, subsequent components will not receive the updated value and will not firereRender. Above we solved the problem of not updating with event subscriptions, but we haven’t solved the problem of not getting new values.mini-create-react-contextConsumerInside the component, via the event subscribergetMethod to get the new value inProviderThe component passes through again internallysetMethod to set the new value, which makes good use of closures to solve the problem of passing the old value to the new value.