问题
I was trying to understand the React through the React library, but couldn't understand what context
and updater
is, which is passed in to the Component.
Following was the code in the library.
function Component(props, context, updater) {
this.props = props;
this.context = context;
this.refs = emptyObject;
// We initialize the default updater but the real one gets injected by the
// renderer.
this.updater = updater || ReactNoopUpdateQueue;
}
What is the purpose of these things?
回答1:
Context
The purpose of context
is to enable devs to pass props
directly to components
, rather than via the props
of children
/ parents
(which can get very complicated / messy).
In some cases, you want to pass data through the component tree without having to pass the props down manually at every level. You can do this directly in React with the powerful “context” API.
Updater
updater
is an object
containing methods
to update the DOM
.
This is evident in lines 61
and 79
.
// Line 61: Enqueue setState.
this.updater.enqueueSetState(this, partialState, callback, 'setState')
// Line 79: Force Update.
this.updater.enqueueForceUpdate(this, callback, 'forceUpdate')
These methods
are triggered using setState() and forceUpdate() respectively.
来源:https://stackoverflow.com/questions/48106784/what-are-context-and-updater-arguments-in-the-react-library