react conText
Using API React.createContext
returns a component object that can use the structure
-
the first way
Components wrapped withProvider
can get the provider’svalue
-
Context. Consumer
The function is used in the component. The function returns a component. The parameter of the function is the parameter initialized byContext
-
the second way
- Wrap all components with
Context.Provider
- Context created by using
static contextType = in the subcomponent will automatically look up and then you can get the value through
this.context
inside the component
Portals slot
A dom
can be inserted under other dom
ReactDOM.createPortal
(the node that needs to be inserted, the node that needs to be mounted)
React. createPortal(Component, nodeElement)
HOC
- The main function is to extract
state
and reuse logic. The operation method can directly use theES7
decorator - Pass in a component to a function, return a component, and extract the common logic from the function
- For example: each page needs to load data and render the page, then the public data acquisition interface can be extracted and the specified component can be rendered
hoc
life cycle component'sdidMount -> hocDidMount -> hocwillMount -> hocwillUnMount -> unMount
HOC has a common problem that props may be repeated
For example:
- Each component has a common operation. For example:
A component
needs to modify the nameB component
also needs to modify the name to upgrade the state usingHOC
Pass in the modification event and the passed in value Loading
operation Each component has aloading
state Usehoc
to receive aloading
status and then use this Theloading
status control shows whether theloading
component or the business component- Data request Two sets of the same data request are placed in different display components for rendering, and the operation of obtaining data can be extracted
Mouse movement example All components need to get the mouse movement x y within a certain component
const withMouse = Component => {<!-- --> return class extends React. Component {<!-- --> state = {<!-- --> x: 0, y: 0 }; handleMouseMove = event => {<!-- --> this.setState({<!-- --> x: event.clientX, y: event.clientY }); }; render() {<!-- --> return ( <div onMouseMove={<!-- -->this.handleMouseMove}> <Component {<!-- -->...this.props} mouse={<!-- -->this.state}/> </div> ); } } }
RenderProps
Surprisingly similar to HOC
. There will be no more duplication of props
. In fact, it is a callback function to obtain external data
// for example Put repeated actions inside the component The component internally calls the external render method to realize that the external component can obtain the internal state of the component so as not to affect the transmission of props class Mouse extends React. Component {<!-- --> static propTypes = {<!-- --> // render: required }; state = {<!-- --> x:0, y:0 }; handleMouseMove = (event) => {<!-- --> this.setState({<!-- --> x: event.clientX, y: event.clientY }) }; render() {<!-- --> return ( <div onMouseMove={<!-- -->this.handleMouseMove}> {<!-- -->this.props.render(this.state)} </div> ); } }
Refs Forward
- The main reason is that it is inconvenient to obtain the
ref
of the leaf component. Usingref
forwarding can accurately obtain theref
of the leaf component
const ref = React.createRef() React.forwardRef((props, ref) => {<!-- --> <Component ref={<!-- -->ref}> })
ref will become the ref of the leaf component
Fragments
- Mainly in the code logic to these components will not generate any additional nodes
<> <div>hello</div> </>
React.lazy React.suspense lazy loading
React. lazy(() => import('./Component'));
- In the past,
webpack
packaged everything into one file, resulting in a particularly large file, which is not conducive to code splitting. At this time, code splitting is required const OtherComponent = React.lazy(() => import('./OtherComponent'));
If there are multiple lazy loaded components, the display will be displayed with the longest loading time componentReact.suspense
parameterfallback
content to be displayed during lazy loading
Principle Analysis
- When the parent component renders to the child component, an asynchronous request is found and an error is thrown directly. The captured result is a
promise
ComponentDidCatch
captures thispromise
exceptionpending
and rendersfallback
- Re-
render
whenresolve
encounters the next asynchronous request and repeats the above operation - Until the
promise
object thrown by the entire parent component willresolve
replaceloading
with the real component
HOOK hook
HOOK
provides a series of hooks for functional components
const [value, setValue] = useState();
value
is the state
state setValue
is a function that needs to set a value and directly calls setValue
to pass in the value that needs to be set. Can
useEffec
t Pass in an anonymous function. The anonymous function is equivalent toDidMount
andDidUpdate
. You can return a function in the anonymous function
The difference between Component and PurComponent
The difference: the former comes with a shallow comparison of props
and state
to achieve shouldComponentUpdate
while the latter does not only need props
to change will re-render
- Disadvantages of PurComponent
False negative judgments may be generated due to inconsistencies in deep data, so that the interface cannot be updated
Why it happens: the new object simply refers to the original object, and changing the new object will affect the original object, such asfoo = {a: 1} bar = foo bar.a = 2
This time zone comparisonfoo
andbar
are the same. The general solution is to use deep copy to refer toimmutable
and optimize it
Cut and anti-shake
- Throttle Control triggers once at a specified time Cannot be called more than once within a specified time
- Debounce Debounce ensures that a function will not be executed a certain amount of time after the last call
requestAnimationFrame
Throttling The browser will ensure that 60 frames per second can prevent operations exceeding 60 frames per second and limit the flow by itself
setState
Asynchronous processing Adding data multiple times will result in unexpected return of data, which can be processed in the form of functions
Why use asynchronous processing?
setState
will not immediately change the value ofReact
components andstate
setState
triggers a redraw by triggering a component update- The effects of multiple
setStat
e function calls will be merged
Reference: Vision published on aoppp.com