useState
useState adds some internal state to the component by calling it in the function component. React will retain this state when rendering repeatedly. useState
A pair of values will be returned: the current state and a function that lets you update it, which you can call in the event handler or some other place. It's similar to the class component
, but it does not merge the new state and the old state.
Next, let’s take an example to see how to use useState.
There is a requirement:Need to load external web pages in iframe。
We pass the initial codeFunctional ComponentsTo achieve this requirement,Just simply render an iframe:
import React, { useState } from 'react'; import styles from './'; function Link(props) { const { match: { params: { link = '' } = {} } = {} } = props; const enCodeUrl = decodeURIComponent(link); const url = ('http') ? enCodeUrl : `http://${enCodeUrl}`; return ( <> <iframe title={link} src={url} style={{ width: '100%', height: '100%', verticalAlign: 'top' }} frameBorder="0" /> </> ); } export default Link;
A new requirement is here, we need to add aloading effect, the implementation method is very simple.Listen to the load event of an iframe to set the start and end of loading。
To achieve this requirement, we need to store itloading status,Functional components have no own state, so we have to transform them into class components:
import React from 'react'; import { Spin } from 'antd'; import styles from './'; export default class Link extends { state = { // Store loading status iLoading: true, }; linkLoad() { // Update loading ({ iLoading: false }); } render() { const { match: { params: { link = '' } = {} } = {} } = ; const { iLoading } = ; const enCodeUrl = decodeURIComponent(link); const url = ('http') ? enCodeUrl : `http://${enCodeUrl}`; return ( <> <Spin spinning={iLoading} wrapperClassName={styles['iframe-loading']}> <iframe onLoad={(this)} title={link} src={url} style={{ width: '100%', height: '100%', verticalAlign: 'top' }} frameBorder="0" /> </Spin> </> ); } }
In order to implement loading of a page, we need to goUsing class, and also needcumbersome behaviors such as binding binding this, this is just a simple requirement, but we can passCome hooksSolve these problems, whileIt can also solve the problem of state reuse among components. We use useState to implement it.。
Import useState import React, { useState } from 'react'; Define the status // The parameter of useState is the initial state value, and setInitLoading is the method of changing the state value const [initLoading, setInitLoading] = useState(true); Update status onLoad={() => setInitLoading(false)} The complete code is as follows: import React, { useState } from 'react'; import { Spin } from 'hzero-ui'; import styles from './'; function Link(props) { const { match: { params: { link = '' } = {} } = {} } = props; const [initLoading, setInitLoading] = useState(true); const enCodeUrl = decodeURIComponent(link); const url = ('http') ? enCodeUrl : `http://${enCodeUrl}`; return ( <> <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> </> ); } export default Link;
Let's take a look at the precautions for useState
Parameters of useState
The parameters of useState can be either a basic type or an object type. 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 = ; setParams({ ...params, []: }); };
Status dependency
If 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 updated, and then the calculated result is returned as the return value.
Summarize
Using useState hooks allows functional components to have state management features. It is similar to the state management of traditional class components, but it is more concise and does not need to use this frequently. In the following article, we will introduce how to combine other hooks to separate business logic so that component code and hooks code perform their own duties.