useState
Next, let's take a look at an example to see how to use useState. There is a requirement: you need to load an external web page in an iframe . In the initial code, we use functional components to achieve this requirement, which only requires a simple rendering of an iframe : import React, { useState } from 'react'; import styles from './index.less'; function Link(props) { const { match: { params: { link = '' } = {} } = {} } = props; const enCodeUrl = decodeURIComponent(link); const url = enCodeUrl.startsWith('http') ? enCodeUrl : `http://${enCodeUrl}`; return ( <React.Fragment> <iframe title={link} src={url} style={{ width: '100%', height: '100%', verticalAlign: 'top' }} frameBorder="0" /> </React.Fragment> ); } export default Link; A new requirement has come. We need to add a loading effect to the page. The implementation method is very simple. Listen to the load event of the iframe to set the start and end of loading . To achieve this requirement, we need to store the loading status , but functional components do not have their own status, so we have to transform them into class components: import React from 'react'; import { Spin } from 'antd'; import styles from './index.less'; export default class Link extends React.Component { state = { //Store loading status iLoading: true, }; linkLoad() { // Update loading this.setState({ iLoading: false }); } render() { const { match: { params: { link = '' } = {} } = {} } = this.props; const { iLoading } = this.state; const enCodeUrl = decodeURIComponent(link); const url = enCodeUrl.startsWith('http') ? enCodeUrl : `http://${enCodeUrl}`; return ( <React.Fragment> <Spin spinning={iLoading} wrapperClassName={styles['iframe-loading']}> <iframe onLoad = {this.linkLoad.bind(this)} title={link} src={url} style={{ width: '100%', height: '100%', verticalAlign: 'top' }} frameBorder="0" /> </Spin> </React.Fragment> ); } } In order to realize the loading of a page, we need to use class , and we also need to bind this and other cumbersome behaviors . This is just a simple requirement, but we can solve these problems through hooks , and at the same time solve the problem of state reuse between components. We use useState to achieve it . Import useState import React, { useState } from 'react'; Define the state // The parameter of useState is the initial value of the state, and setInitLoading is the method to change the state value const [initLoading, setInitLoading] = useState(true); Update state onLoad = {() => setInitLoading(false)} The complete code is as follows: import React, { useState } from 'react'; import { Spin } from 'hzero-ui'; import styles from './index.less'; function Link(props) { const { match: { params: { link = '' } = {} } = {} } = props; const [initLoading, setInitLoading] = useState(true); const enCodeUrl = decodeURIComponent(link); const url = enCodeUrl.startsWith('http') ? enCodeUrl : `http://${enCodeUrl}`; return ( <React.Fragment> <Spin spinning={initLoading} wrapperClassName={styles['iframe-loading']}> <iframe onLoad = {() => setInitLoading(false)} title={link} src={url} style={{ width: '100%', height: '100%', verticalAlign: 'top' }} frameBorder="0" /> </Spin> </React.Fragment> ); } export default Link; Let's take a look at the useState precautions below useState ParametersThe parameters of useState can be either primitive types or object types. When updating the object type, remember to merge the old state, otherwise the old state will be lost. const [params, setParams] = useState({ rotate: 0, color: "#000000" }); const handleInputChange = event => { const target = event.target; setParams({ ...params, [target.name]: target.value }); }; State DependencyIf the current state needs to be calculated based on the value of the last updated state, a function is passed to the function that updates the state. The first parameter of this function is the value of the last update, and the calculated result is returned as the return value. SummarizeThe useState hook allows functional components to have state management features, which is similar to the state management of traditional class components, but more concise and does not require the frequent use of this. In the following articles, we will introduce how to combine other hooks to extract business logic so that component code and hooks code can perform their respective functions. You may also be interested in:
|
<<: Database query optimization: subquery optimization
>>: Detailed example of SpringBoot+nginx to achieve resource upload function
In the path of using nginx as a reverse proxy tom...
This article introduces a detailed explanation of...
1. flex-direction: (direction of element arrangem...
This article shares the specific code of JavaScri...
In enterprises, database high availability has al...
Enter Alibaba vector icon library Alibaba Vector ...
Table of contents 1. TypeScript is introduced int...
An at-rule is a declaration that provides instruc...
Introduction When writing SQL today, I encountere...
React is different from Vue. It implements route ...
Preface When using Docker in a production environ...
The difference between CSS3 animation and JS anim...
In the previous article, after configuring the we...
Table of contents Functional Components How to wr...
Table of contents MySQL slave library Seconds_Beh...