The basic use of State in component programming

State is the state information contained in a component. The so-called “state” refers to the various data stored in the component at any time. The most important thing about state is that when a component updates state, it triggers a re-rendering of the component, which can be considered a partial refresh. For example, if you want to display dynamically changing data in a component’s DIV tag, if you store the data as global variables, the component will still display the same data even if the variables are updated, because the component is not re-rendered.

UseState () for functional components

The most common thing we use with React is class-based components. However, while the class component definition and use of state are clear, sometimes the code may not be very easy to write. Especially when we learn to use some ready-made graphics libraries, such as Antd and Antv, the official implementation of some practical functions are all written using functional components, forcing the code into class components will cost a lot of time. So how do functional components define and use component state?

Initialize the state

When initializing state in a class component, you can write a sentence directly

state = {
    key1:... .key2:... }Copy the code

The class component state is initialized.

The useState() function is more like handling each key individually. For example, we coded our component like this:

Child.js

import React, {useState} from "react";

const Child = () = > {
    // Set a state property content, the initial value is the string 'initial state'
    // The initial value can be any type of variable, including string, Boolean, list, dictionary object, etc
    const [content] = useState('Initial state')
    return (
        <div>
            {content}
        </div>)}export default Child
Copy the code

So we mount the component Child in app.js on the main page and get its basic display:

Update the state

Updating state in functional components should try to call setAttr as canonical as possible:

import React, {useState} from "react";

const Child = () = > {
    For example, if my property is called content, try to call its set function setContent. Of course, it's okay to call it something else, but it's not very formal
    const [content, setContent] = useState('Initial state')
    return (
        // You can also call setContent by calling the function, passing the set function the value you want to update
        <div onClick={()= >{content===' initial state '? SetContent (' new state ') : setContent(' initial state ')}} ></div>)}export default Child
Copy the code

The following results are obtained:

State is initialized via a function callback

Sometimes we do want to initialize state as soon as the component is loaded, for example, loading a list of data, but the list of data needs to be fetched from the back end, so there are several ideas:

  1. If the parent component clicked a button to access or render the child component, why not write a function on the parent component to fetch the data, then update the parent component state and pass the data to the child component as props
  2. Subcomponents are defined as class components that perform data fetching and setState() in ComponentDidMount() (highly recommended! This causes two child components to mount.)
  3. Subcomponent functional component definition, pre-defined getData function, directly returns the data obtained

I did use Tip number three for functional components.

The general encoding mode is as follows:

Child.js

import axios from "axios";
import React, {useState} from "react";

const Child = () = > {
    const getInit = () = > {
        axios(url='xxxx', method='POST', other attributes...) .then(request= >{how to handle the server responsereturn request.data
            },
            error= >{
                alert(error)
                returnSome custom error messages})}const [content, setContent] = useState(getInit)
    

    return (
        // You can also call setContent by calling the function, passing the set function the value you want to update
        <div>
            {content}
        </div>)}export default Child
Copy the code