In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to learn React-Hook". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to learn React-Hook.
Data binding
In react, the concept of state is the management of internal state, and its changes will directly affect the rendering of the page.
The setState is taken apart in hook. Each individual state will be a single state, and the change of a single state will not affect other state. We can implement the initialization definition of a single state through useState.
The argument to useState can be a number, a string, a Boolean, an array, an object, or a function.
Similarly, we can't avoid using collections (objects) to deal with some logic.
Const [count, setCount] = useState (0); const [count, setCount] = useState (() = > 0); const [obj, setObj] = useState ({}); setObj ((prevObj) = > {/ / Object.assign return {... prevObj, age: 23};})
Generally, we will define an initial value initialState, if this initial value requires additional computational overhead, we can define a function to deal with it. It is important to note that the useState function is called only during the initial rendering.
Const [state, setState] = useState (() = > {/ / additional operation someExpensiveComputation const initialState = someExpensiveComputation (props); return initialState;})
Another solution for dealing with multiple state collections is useReducer.
For example, when the state of a single state affects the values of multiple state.
For example, the state of multiple state will change with some type of change.
Several of the following state will change as you log in, log out, and refresh the token.
Const [state, dispatch] = React.useReducer ((prevState, action) = > {switch (action.type) {case "RESTORE_TOKEN": return {... prevState, userToken: action.token, isLoading: false,} Case "SIGN_IN": return {... prevState, isSignout: false, userToken: action.token,}; case "SIGN_OUT": return {... prevState, isSignout: true, userToken: null,} }, {isLoading: true, isSignout: false, userToken: null,})
Side effect
Hook provides a new concept to replace lifecycle functions, which are useEffect side effects. It is seen as an escape route from the pure functional world of React to the imperative world.
The timing of its execution is to delay execution after the rendering of the screen element is finished.
Its functions are as follows:
It can monitor the change of state value.
It can handle logic that runs only once, somewhat similar to the thinking patterns of lifecycle componentDidMount and componentWillUnmount.
Add subscriptions, set timers, send network requests
More others
/ / use the second parameter to execute only once or monitor the state value useEffect (() = > {/ /.}, []); / / the return function of the first parameter of useEffect is the idea of componentWillUnmount, useEffect (() = > {const subscription = props.source.subscribe (); return () = > {/ / clear subscription subscription.unsubscribe ();};})
However, this delayed execution mechanism can not meet all our scenarios. If we want to achieve simultaneous execution of screen rendering and side effects, such as real-time modification of dom structure, useEffect can not meet the requirements, and there will be a splash screen effect.
We can do this through useLayoutEffect, which is executed after the component is loaded and before the screen is drawn. However, this also has the disadvantage of blocking screen rendering, which may cause a blank screen or pause.
So the usage scenario of useLayoutEffect:
Prevent flicker, more time-consuming calculation
Dom operation
Scenes of componentDidMount and componentDidUpdate
There is no need to use useLayoutEffect if it is just a separate fetch (get operation).
Component passing value
The core of the value passed by the component:
The parent passes on the child by setting the properties in the child component
The son passes on the father, through the callback.
Multi-level components, managed through intermediate state
/ / parent component function Home () {const [currentTab, setCurrentTab] = useState ("msg"); return (/ / parent / child / parent setCurrentTab (code)} / > {currentTab}) } / / subcomponent function TabView ({currentTab, setCurrentTab}) {return ({currentTab} {setCurrentTab ("pass");}} / >);} / / parent function CodeView ({code, changeCode}) {return ({code});}
The value passed by multiple components can be handled by context.
Export const MyContent = React.createContext ({}); function Home () {return ();} function FormItem () {const {phoneValue, setPhoneValue} = useContext (MyContent); return ({phoneValue} {/ *... * /});} function SwitchItemView () {const {codeValue, setCodeValue} = useContext (MyContent) Return ({phoneValue} {/ *... * /});}
Element node operation
Hook creates a node object through useRef, then mounts it through ref and gets it through current.
Function TextInputWithFocusButton () {const inputEl = useRef (null); const onButtonClick = () = > {inputEl.current.focus ();}; return (Focus the input);}
We may encapsulate some logic, customize some attributes, expose to the parent element, and then we will use useImperativeHandle and forwardRef.
Function FancyInput (props, pref) {const inputRef = useRef (); useImperativeHandle (ref, () = > ({focus: () = > {inputRef.current.focus ();}})); return;} FancyInput = forwardRef (FancyInput); / / parent component can call inputRef.current.focus () directly
Because the ref object does not notify us of changes in the current ref value, we must implement it through useState and useCallback.
Function MeasureExample () {const [height, setHeight] = useState (0); const measuredRef = useCallback ((node) = > {if (node! = = null) {setHeight (node.getBoundingClientRect () .height);}, []); return (Hello, world The above header is {Math.round (height)} px tall);}
Custom hook
In the code, we will have some common logic that we can extract, such as custom anti-jitter throttling, custom Hook is a function whose name starts with "use", and other Hook can be called inside the function.
Const useDebounce = (fn, ms = 30, deps = []) = > {let timeout = useRef (); useEffect () = > {if (timeout.current) clearTimeout (timeout.current); timeout.current = setTimeout (() = > {fn ();}, ms);}, deps); const cancel = () = > {clearTimeout (timeout.current); timeout = null;}; return [cancel];}; export default useDebounce Const Home = (props) = > {const [a, setA] = useState (0); const [b, setB] = useState (0); const [cancel] = useDebounce (() = > {setB (a);}, 2000, [a]); const changeIpt = (e) = > {setA (e.target.value);}; return ({b} {a});}
Performance optimization
Unidirectional data flow, the level of each component is clear, the state is clear, but when the project volume is large and the components are nested, the performance loss is also very large, so we will do some performance optimization work.
Possible optimization scenarios are:
Updates to a single state will affect the overall situation. It is important to note that components wrapped by context will be re-rendered as soon as any change in value is made, and useMemo and useCallback will be invalidated.
Same input, no recalculation
The function of the parent component is used by the child component
In fact, the core idea of useMemo and useCallback is to record the last input. If the next input is the same as the previous one, it will not be calculated and the last result will be obtained directly. The difference between them is only formal, useMemo returns a memoized value. UseCallback returns the memoized callback function.
UseMemo caches the value of the calculation result.
UseCallback is mainly used for caching functions.
UseCallback (fn, deps) is equivalent to useMemo (() = > fn, deps).
Const memoizedCallback = useCallback (() = > {doSomething (a, b);}, [a, b]); / / useMemo const [count, setCount] = useState (1); const [val, setValue] = useState (""); const expensive = useMemo (() = > {let sum = 0; for (let I = 0; I)
< count * 100; i++) { sum += i; } return sum; }, [count]); return ( {count}-{expensive} {val} setCount(count + 1)}>+ C1 setValue (event.target.value)} / >)
Take a look at memoized, which is simply caching the evaluation results of a function, such as recursion.
Const memoize = function (fn) {const cache = {}; return function () {const key = JSON.stringify (arguments); var value = cache [key]; if (! value) {console.log ('new value, executing...'); / / in order to understand the log added by the process, value = [fn.apply (this, arguments)] should be removed formally. / / put it in an array to deal with exceptions such as undefined,null cache [key] = value;} else {console.log ('from cache'); / / in order to understand the log added by the process, you should remove} return value [0];}} module.exports = memoize Const memoize = require ('. / memoize.js'); const log = console.log; / / Fibonacci array const fibonacci = (n) = > {return n < 2? N: fibonacci (n-1) + fibonacci (n-2);}; const memoizeFibonacci = memoize (fibonacci); log (memoizeFibonacci (45)); / / New value, executing...; 1134903170 / / long waiting time log (memoizeFibonacci (45)); / / from cache; 1134903170 log (memoizeFibonacci (45)); / from cache; 1134903170 log (memoizeFibonacci (45)); / from cache 1134903170 so far, I believe you have a deeper understanding of "how to learn React-Hook". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.