“This is the third day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021.”
[Previously] Used in class componentsstate
class Layout extends React.Component {
state = {
loading: true
}
componentDidMount() {
this.setState({ loading: false})}render() {
const { loading } = this.state;
const { children, isLogin } = this.props;
if(! isLogin || loading) {return (
<div>loading...</div>)}return ( children )
}
}
Copy the code
usehook
Implementation uses state and other React features without writing a class component
The multiple calls to useState and useEffect in a component are completely independent
useState
Modify component state in a function group. 【React initial contact 】 【React initial contact
const [state, setState] = useState(initialVal);
import { useState } from 'react';
export default(props? :any) = > {// useState passes in the initial state argument and returns the current state and the function to update the state
const [count, setCount] = useState(() = > {
return someExpensiveComputation(initialCount);
})
return (
Count: {count}
// Form 1: setCount passes the updated value
<button onClick={() = > { setCount(initialCount) }}>reset</button>
// setCount is passed to the function
<button onClick={()= > setCount(preCount => preCount - 1)}> - </button>
<button onClick={()= > setCount(preCount => preCount + 1)}> + </button>)}Copy the code
useEffect
Side effects: get data, set up subscriptions, and manually change the DOM in the React component
useEffect(didUpdate)
Run some extra code after react updates the DOM, using this hook to tell the component what to do. React saves this function and calls it after a DOM update.
- Execution time:
-
Default: executes after the first rendering and after each update (ensure that the DOM is updated each time, after the browser has finished laying out and drawing).
-
Conditional execution: Pass useEffect a second argument as an array of dependent values, in which any changes will trigger the function call
P.S. ensures that the array contains all variables in the external scope that change over time and are used in effect, otherwise the code will introduce previous variables.
-
Special usage: useEffect is executed only once when the component is mounted and unloaded when the second argument is an empty array
Effect does not depend on props or state, so it does not need to be executed repeatedly.
// Update only when count changes
useEffect(() = > {
document.title = `you click ${count} times`;
}, [count])
// Updates only when the component is mounted
useEffect(() = > {
document.title = `you click ${count} times`;
}, [])
Copy the code
- Remove:
-
Effect that does not need to be cleaned
-
Effect to clear: returns a clean function that will clear the previous effect before the next effect executes
UseEffect to resolve a common error
Warning: Can’t perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
Solution: Operating on state when the component is not rendered generates an error (common with setTimeout, etc.)
- Class component usage
componentWillUnmount
componentWillUnmount(){
clearTimeout(id)
}
Copy the code
- UseEffect Passes in the cleanup function
const [isOnline, setIsOnline] = useState(null)
useEffect(() = > {
const id = setTimeout(() = >{... })return () = > {
clearTimeout(id)
}
}
Copy the code