preface
Maybe it really smells good!! After all, I also want to React, although my current technology stack is Vue. This is a review and learning article
After two years, I recall React again, which is a long time and miss the taste, why say so?
In June and July 2018, under the leadership of an IOS colleague, I used React Native to make an App related to data analysis for the company, and then I used React to write a background application successively. During this period, I was deeply inspired by the development mode of my colleague. Components are highly reusable… And so on have a new understanding and understanding; At the same time, ALSO deeply like React.
Actually, what I miss is…… Then I switched jobs, from React back to Vue (for the simple reason that the new company Unified Technology Stack Vue); All right, back to the point.
What is the Hook?
A Hook is a function that allows you to “Hook” properties such as React state and lifecycle into a function component. In other words, once we only used properties such as state and lifecycle in class components, now it is a characteristic function that can be used in a function component. Hooks cannot be used in class components
Meet Hook!
Hook the practice
Here, I will not paste the code and narration bit by bit. The official document is very clear about the hook API. I will directly write the practical code about most API of hook, and you can understand it after reading the comments.
/** * Hook is a function that allows you to "Hook" the React state and lifecycle features in a function component. ** hooks cannot be used in a class component */
import React, {
useState,
useEffect,
useContext,
useReducer,
useCallback,
useMemo,
useRef
} from "react"
import { ContextObj } from ".. /home"
import { prestyle, divstyle } from './style'
// Lazily initialize count
function GetA () {
return 0;
}
// Reducer initializes state and defines logic methods
const initState = { count: 0 }
/ / reducer method
function reducer (state, action) {
switch (action.type) {
case "add":
return { count: state.count + 1 }
case "jian":
return { count: state.count - 1 }
default:
throw new Error()}}// useCallbackFn callback function
function useCallbackFn (count) {
return count * 2;
}
// Modify the external function of count
function setCountFun (count) {
return count + 1;
}
/ / hook component
function Example (props) {
// useState
// Define methods to initialize state and modify state
// Lazily initialize count, using a function to get the initial state. The variables count, GetA() are defined above
const [count, setCount] = useState(() = > {
const a = GetA();
return a;
});
// Initialize count2 ↓ by default
const [count2, setCount2] = useState(0);
// useEffect
// Equivalent to the life cycle of class components
// componentDidMount The mounting is complete
// componentDidUpdate Update completed
// componentWillUnmount before destruction
// The second parameter is the dependency value, and the empty array is executed only once. If the dependency value changes, the useEffect hook is executed
useEffect(() = > {
console.log("Hook - useEffect() print count:", count, props);
setCount2(count * 10)
}, [count]) // [] : no trigger
// useContext
/ / the father... Const ContextObj = React.createcontext () const ContextObj = React.createcontext ()
// ContextObj must be the entire context
const value = useContext(ContextObj);
// useReducer
// Initialize state and its corresponding modification methods
// Reduce (reducer); accept two parameters, the old state state and the new state action
// initState, which initializes the value of state, is lazy
// Dispatch an action to trigger the corresponding reducer method
const [state, dispatch] = useReducer(reducer, initState);
// useCallback => useMemo syntax sugar
// useCallbackFn, execute the logic
// Array, dependency, pass the corresponding value of the dependency, and execute only if the value changes
const memoCallback = useCallback(useCallbackFn, []);
// useMemo is similar to useCallback
// fn to create the logical function
// Array, dependent
const memoValue = useMemo(() = > { return count * 3 }, [count]);
// useRef returns a variable ref object
// The parent component calls the properties and methods of the child component through ref: the child component uses useImperativeHandle(ref,fun)
// Ref is passed in and fun is defined as the called method and property
Export default forwardRef(subcomponent)
// For example, see menu. JSX
const inpRef = useRef(null);
return (
<div style={divstyle}>
<div>
<p>Received props random value {props. Random}</p>
<h3>UseState counter count: {count}</h3>
<h3>UseEffect listener count x 10 = {count2}</h3>
<button onClick={()= > setCount(setCountFun(count))}> click + </button>
<button onClick={()= > setCount(count - 1)}> click - </button>
<hr />
<h3>UseContext context: {value}</h3>
<h3>Count * 2 = {memoCallback(count)}</h3>
<h3>Count * 3 = {memoValue}</h3>
<h3>UseRef gets a mutable object - input box
<input type="text" ref={inpRef} />
<button onClick={()= >{inpref.current.focus ()}}> Get the focus</button>
</h3>
<h3>UseLayoutEffect is similar to useEffect, the difference is: useLayoutEffect is synchronous render blocked, useEffect is not blocked</h3>
<h3>UseDebugValue I did not practice, interested students can have a try</h3>
<hr />
<h3>useReducer Count:{state.count} </h3>
<button onClick={()= > { dispatch({ type: "add" }) }}>useReducer +</button>
<button onClick={()= > { dispatch({ type: "jian" }) }}>useReducer -</button>
</div>
</div>
);
}
export default Example;
Copy the code
conclusion
Through a case above, also do not know each student to have understood, but also not important, why? Because only code code can a programmer learn the essence efficiently, so I specially wrote a community application based on Hook. Of course, not only the common knowledge points of Hook and React, including Redux, have been reviewed respectively. Appreciate the
Hook Community of Practice [Learn, learn, learn, keep up with the pace]
Login page - Two entries
Community home page contains [registration - login - right ladder navigation]
Right trapezoidal navigation
Login - register
The article details
【 Review clips 】
Redux tag fragment
Hooks tag fragment
I will not show you the rest of the source code
In line with my own thoughts of reviewing React, learning Hook and sharing with you, I wrote this little application. You can make fun of it and make fun of it. It mainly contains the following contents: it can be divided into two categories
1, review React common knowledge life cycle, Context, Refs, Fragment, Hoc, Portals, Hooks, Redux contain remarks and source guide
2, Hook practice to write a community application basically using the built-in Hook common knowledge points including remarks and source guide
Go complete code ~ biu ~ biu ~ biu view
If you encounter the following problems:
Corresponding processing
I can’t see what the problem is ~~~~
Welcome to like, a little encouragement, a lot of growth