美文网首页
01-React-hooks-useState基本使用

01-React-hooks-useState基本使用

作者: 低头看云 | 来源:发表于2020-11-01 09:18 被阅读0次

    React-hooks-useState

    useState的基本用法

    格式:

     const [state, setState] = useState(initialState); 
    

    初始状态

    • useState的第一个参数是初始状态

    读取状态

    • 当useState(initialState)被调用时返回一个数组
    • 该数组的第一项是状态值
    const stateArray = useState(false);
    stateArray[0];  // false => 状态值
    

    更新状态

    • 用值更新状态
    const [state, setState] = useState(initialState);
    
    // 改变状态值 设置新的值
    setState(newState);
    
    // 之后渲染新的值
    
    • 使用回调函数更新状态
      • 使用回调更新装填,可以解决setState引发异步更新和状态合并
    const [state, setState] = useState(initialState);
    setState(prevState => nextState);
    
    • 示例
    // Toggle a boolean
    const [toggled, setToggled] = useState(false);
    setToggled(toggled => !toggled);
    
    // Increase a counter 
    // 推荐使用回调的方式更新组件状态
    const [count, setCount] = useState(0);
    setCount(count => count + 1);
    console.log(count)  // 1
    setCount(count => count + 1);
    console.log(count)  // 2
    
    // Add an item to array
    const [items, setItems] = useState(["old"]);
    setItems(items => [...items, 'New Item']);
    

    初始值状态计算

    • 计算组件的初始状态很慢。这在类组件中不是问题,因为初始状态计算仅在构造函数中发生一次,但是在函数组件中,初始状态计算在render函数中声明,并且在每次渲染时都发生。因此,缓慢的初始状态计算会大大降低整个应用程序的速度。
    useState(/* Slow computation */)
    
    • useState 还可以将函数作为参数而不是值作为参数,并且该函数将仅在首次呈现组件时运行。通过使用此功能的版本,useState您将不再在每次渲染时运行缓慢的计算,而是像类组件一样在组件的第一个渲染中仅运行一次。

    使用useState()的陷阱

    • 使用useState()钩子时,只能在函数顶层调用挂钩
    • 不能在循环,条件,嵌套函数中使用useState()调用
    • 在多次调用中,调用以相同的顺序
    • useState()只能在函数式组件中调用,不能在class类中使用
    • 不可以在嵌套函数中调用

    注意点示例

    可以多次调用useState(),调用以相同的顺序

    function Bulbs() {
      // Good
      const [on, setOn] = useState(false);
      const [count, setCount] = useState(1);
      // ...
    }
    

    无效调用useSate()

    • 在if语句中,错误的调用
    function Switch({ isSwitchEnabled }) {
      if (isSwitchEnabled) {
        // Bad 错误用法
        const [on, setOn] = useState(false);
      }
      // ...
    }
    
    • 在嵌套函数中被错误的调用
    function Switch() {
      let on = false;
      let setOn = () => {};
    
      function enableSwitch() {
        // Bad
        [on, setOn] = useState(false);  }
    
      return (
        <button onClick={enableSwitch}>
          Enable light switch state
        </button>
      );
    }
    

    相关文章

      网友评论

          本文标题:01-React-hooks-useState基本使用

          本文链接:https://www.haomeiwen.com/subject/irdyvktx.html