发布于 2026-01-06 0 阅读
0

React Hooks:useState

React Hooks:useState

在我知道 React Hooks 之前,我经常看到这样的建议:“在 React 中始终使用函数式组件而不是类组件。 ” 这意味着始终将组件声明为函数而不是类。或者用代码来说:

//use
const Component = ()=>{
  // return code here 
}

//instead of 
class Component extends React.Componet{
    render(){
       // return code here 
    }
}
Enter fullscreen mode Exit fullscreen mode

我尝试了一段时间遵循那个建议。然而,当我想要state在组件中使用它时,那个建议却显得毫无用处。我不得不重构代码,使用类组件而不是函数组件。我当时以为这是在 React 中使用生命周期方法state的唯一途径。但我当时的想法完全错了。

后来我了解了钩子技巧,那些建议也就变得更有意义了。

我目前了解到的 React Hooks 的几点是:
1. Hooks 允许我们使用state一些特性,而无需编写类。2
. 我们只能在函数式组件中调用 Hooks。3
. 我们只能在顶层调用 Hooks,不能在循环、条件语句或嵌套函数中调用。

让我们编写一个简单的类组件来改变元素的背景颜色div,然后看看如何重构它以使用useState钩子。

class App extends React.Component {
    constructor(props){
      super(props);
      this.state= {
         backgroundColor: "lightblue",
      }
    }
    changeBackgroundColor = ()=>{
     this.setState({ backgroundColor: getRandomColor() })
    }
    render(){
        return(
         <main>
             <div 
                style={{backgroundColor:this.state.backgroundColor }} 
                className="circle"
              />
             <button onClick={this.changeBackgroundColor}>Change Color</button>
         </main>
        )}
}
const getRandomColor = ()=>{
   return "#" + Math.random().toString(16).slice(2,8);
}
Enter fullscreen mode Exit fullscreen mode

这段代码看起来很长,但功能却只是随机改变背景颜色,对吧?

让我们来看看使用钩子函数后会发生哪些变化useState

import React, { useState } from 'react';
const App =()=> {
    // 1
    let [backgroundColor, setBackgroundColor] = useState("lightblue");
    const changeBackgroundColor = ()=>{
      // 2
      setBackgroundColor(getRandomColor())
    }
    return(
      <main>
          {/* 3 */}
          <div 
            style={{backgroundColor:backgroundColor}} 
            className="circle"
          />
          {/* 4 */}
          <button onClick={changeBackgroundColor}>Change Color</button>
      </main>
    )}
Enter fullscreen mode Exit fullscreen mode

首先this.state,我们用一行代码替换了编写构造函数和使用它的四行代码。

// Old code
constructor(props){
      super(props);
      this.state= {
         backgroundColor: "lightblue",
     }
}

// New code
let [backgroundColor, setBackgroundColor] = useState("lightblue");
Enter fullscreen mode Exit fullscreen mode

其次,我们不再需要使用this.setState更新state变量的方法了。

// Old code
this.setState({ backgroundColor: getRandomColor() })

//New code
setBackgroundColor(getRandomColor())
Enter fullscreen mode Exit fullscreen mode

最后,我们不再需要因为使用大量的“this和”而感到困惑了。this.state.<variable_name>

// Old code
 onClick={this.changeBackgroundColor}
 style={{backgroundColor:this.state.backgroundColor}}

// New code
 onClick={changeBackgroundColor}
 style={{backgroundColor:backgroundColor}} 
Enter fullscreen mode Exit fullscreen mode

让我们仔细看看这行代码:

let [backgroundColor, setBackgroundColor] = useState("lightblue");
Enter fullscreen mode Exit fullscreen mode

你认为这行代码的作用是什么?如果我们想改变的是字体而不是背景颜色,你认为会发生什么变化?

先回答第二个问题,如果我们想更改字体系列,我们会这样写:

Let [fontFamily, setFontFamily] = useState("Arial"); // setting Arial as the initial value of the font-family.

//Or 
Let [font, setFont] = useState("Arial"); // you can name your variables whatever you want.
Enter fullscreen mode Exit fullscreen mode

回到我们最初的问题。你认为这行代码的作用是什么?

let [backgroundColor, setBackgroundColor] = useState("lightblue");
Enter fullscreen mode Exit fullscreen mode

实际上,这行代码做了三件事。1-
它声明了一个名为 `x` 的变量backgroundColor。2-
它给这个变量赋予了一个初始值 `0`。3-lightblue
声明了一个名为 `f` 的函数setBackgroundColor,该函数负责backgroundColor在需要时更新 `x` 的值。

那么,为什么会发生这种情况呢?

当我们调用useState钩子函数并传递一个值时,它会返回一个包含两个元素的数组。第一个元素是一个state变量,其值被设置为传递给钩子函数的值useState。第二个元素是一个函数,负责更新第一个变量的值。

当我们写作时,

let [backgroundColor, setBackgroundColor] = useState("lightblue");
Enter fullscreen mode Exit fullscreen mode

我们使用数组销毁backgroundColor变量和setBackgroundColor函数分配给调用钩子返回的数组中的两个元素useState

最后我想提一下,我们可以useState在组件中多次使用钩子函数。

如果我们想更改组件的背景颜色、字体和边框,我们可以这样写:

const [backgroundColor, setBackgroundColor] = useState("yellow");
const [fontFamily, setFontFamily] = useState("Arial");
const [borer, setBorder] = useState("1px solid teal");
Enter fullscreen mode Exit fullscreen mode

然后分别使用所有setBackgroundColorsetFontFamilysetBorder函数来更新背景颜色、字体系列和边框。

我想这就是我useState目前对这个钩子所知道的全部了。

感谢阅读。

文章来源:https://dev.to/hajarnasr/react-hooks-usestate-2eb