State HooksExamples: import { useState } from 'react'; function Example() { const [count, setCount] = useState(0); //count: declared variable; setCount: function to change count value; 0: initial value of count return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } useState is a hook function that comes with react, and its function is to declare state variables. The parameter received by the useState function is our initial state. It returns an array. The [0]th item in this array is the current state value, and the [1]th item is the method function that can change the state value. When the user clicks the button, we call the setCount function, which receives the new state value as a parameter. The next thing is to leave it to react, which will re-render our Example component. What if a component has multiple state values? function ExampleWithManyStates() { const [age, setAge] = useState(42); const [fruit, setFruit] = useState('banana'); const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]); } Secondly, the initial value received by useState is not required to be a simple data type such as string/number/boolean. It can receive objects or arrays as parameters. The only point to note is that our previous this.setState merged the states and returned a new state, while On the one hand, hook is used directly in function instead of class; on the other hand, each hook is independent of each other, and different components calling the same hook can ensure the independence of their respective states. How does react ensure the independence of multiple useStates? The answer is //First rendering useState(42); //Initialize age to 42 useState('banana'); //Initialize fruit to banana useState([{ text: 'Learn Hooks' }]); //... //Second rendering useState(42); //Read the value of the state variable age (the parameter 42 passed at this time is directly ignored) useState('banana'); //Read the value of the state variable fruit (the parameter banana is ignored at this time) useState([{ text: 'Learn Hooks' }]); //... React stipulates that we must write hooks at the outermost layer of the function, and cannot write them in conditional statements such as ifelse, to ensure that the execution order of hooks is consistent. Effect Hooks Examples: import { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); // Similar to componentDidMount and componentDidUpdate: useEffect(() => { // Update the document title document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); } How would we write it without hooks? class Example extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } componentDidMount() { document.title = `You clicked ${this.state.count} times`; } componentDidUpdate() { document.title = `You clicked ${this.state.count} times`; } render() { return ( <div> <p>You clicked {this.state.count} times</p> <button onClick={() => this.setState({ count: this.state.count + 1 })}> Click me </button> </div> ); } } The stateful components we write usually have many side effects, such as initiating Ajax requests to obtain data, adding some listener registration and unregistration, manually modifying the DOM, etc. We have previously written these side effect functions in life cycle function hooks, such as componentDidMount, componentDidUpdate, and componentWillUnmount. How to unbind some side effects of useEffect ?
import { useState, useEffect } from 'react'; function FriendStatus(props) { const [isOnline, setIsOnline] = useState(null); function handleStatusChange(status) { setIsOnline(status.isOnline); } useEffect(() => { ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); // Be sure to pay attention to this order: tell react to perform cleanup after the next re-rendering of the component and before the next call to ChatAPI.subscribeToFriendStatus return function cleanup() { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); if (isOnline === null) { return 'Loading...'; } return isOnline ? 'Online' : 'Offline'; } How to skip some unnecessary side effects functions? According to the idea in the previous section, these side-effect functions must be executed every time the rendering is re-rendered, which is obviously not economical. How to skip some unnecessary calculations? We just need to pass the second parameter to useEffect. Use the second parameter to tell React to execute the side effect function we passed (the first parameter) only when the value of this parameter changes. useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); // Only when the value of count changes will the sentence `document.title` be re-executed When we pass an empty array [] as the second parameter, it is actually equivalent to executing it only during the first rendering. That is the pattern of componentDidMount plus componentWillUnmount. However, this usage may cause bugs, so use it less often. What other built-in Effect Hooks are there? useContext How to write custom Effect Hooks? Why should we write an Effect Hooks ourselves? This way we can For example, we can extract the function of judging whether a friend is online from the FriendStatus component written above, and create a new useFriendStatus hook specifically for judging whether a certain ID is online. import { useState, useEffect } from 'react'; function useFriendStatus(friendID) { const [isOnline, setIsOnline] = useState(null); function handleStatusChange(status) { setIsOnline(status.isOnline); } useEffect(() => { ChatAPI.subscribeToFriendStatus(friendID, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(friendID, handleStatusChange); }; }); return isOnline; } At this time, the FriendStatus component can be shortened to: function FriendStatus(props) { const isOnline = useFriendStatus(props.friend.id); if (isOnline === null) { return 'Loading...'; } return isOnline ? 'Online' : 'Offline'; } Suppose we have another friend list that also needs to display online information: function FriendListItem(props) { const isOnline = useFriendStatus(props.friend.id); return ( <li style={{ color: isOnline ? 'green' : 'black' }}> {props.friend.name} </li> ); } This enables taro hooksIt is very simple to use the Hooks API in Taro. Taro's proprietary Hooks (such as usePageScroll, useReachBottom) are introduced from @tarojs/taro, and the framework's own Hooks (such as useEffect, useState) are introduced from the corresponding framework. import { usePageScroll, useReachBottom } from '@tarojs/taro' // Taro-specific Hooks import { useState, useEffect } from 'react' // Framework Hooks (Basic Hooks) This concludes this article on the detailed tutorial on how to get started with react hooks. For more relevant introductory content on react hooks, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: MySql multi-condition query statement with OR keyword
>>: In-depth interpretation of /etc/fstab file in Linux system
This article shares the specific code for JavaScr...
#docker search #docker pull portainer 1. Download...
Detailed explanation of Linux LVM logical volume ...
Table of contents Overview 1. Parent component pa...
Preface To help ensure that your web pages have a ...
Table of contents Install Docker on CentOS 8 1. U...
This article example shares the specific code of ...
When processing batch updates of certain data, if...
Vue3.0 has been out for a while, and it is necess...
Table of contents Overview (Loop Mode - Common) D...
Alibaba Cloud Server cannot connect to FTP FileZi...
In the process of database operation, it is inevi...
Preface: Docker is an open source application con...
Overview The cloud platform customer's server...
Vue encapsulates the breadcrumb component for you...