【问题标题】:conceptual understanding of square bracket destructuring in reactreact中方括号解构的概念理解
【发布时间】:2021-03-17 19:38:21
【问题描述】:
import React, { useEffect, useState } from 'react'
import { Text } from 'react-native'

export default function Counter() {
  const [count, setCount] = useState(0)

  useEffect(() => {
    const id = setInterval(() => setCount((count) => count + 1), 1000)

    return () => clearInterval(id)
  }, [])

  return <Text style={{ fontSize: 120 }}>{count}</Text>
}

那么count和setCount是如何从useState(0)中获取值的

const [count, setCount] = useState(0)

你能像我五岁一样陪我度过这个困惑吗?

【问题讨论】:

标签: javascript reactjs destructuring


【解决方案1】:

useState 挂钩只返回一个包含两个值的数组:第一个是您要在组件中使用的值,第二个是您可以调用以更改值的函数。 useState 钩子接受一个允许您设置初始值的参数。

如需进一步阅读,请参考 React 文档:https://reactjs.org/docs/hooks-state.html

括号符号只是解构 useState 挂钩返回的数组,以便您可以轻松地在组件中访问它的值。

【讨论】:

    【解决方案2】:

    函数useState 返回一个包含两个值(有状态值和设置器)的数组。这样做是为了让单个函数调用可以一次返回两个值(JavaScript 作为一种语言不支持这一点,但其他语言确实支持这样的东西)。

    例子:

    function neighbors (num) {
      return [num - 1, num + 1]
    }
    
    const [seven, nine] = neighbors(8)
    

    见:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#array_destructuring

    【讨论】:

      【解决方案3】:

      每 1000 毫秒(1 秒)之后

      useEffect(() => {
          const id = setInterval(() => setCount((count) => count + 1), 1000)
      
          return () => clearInterval(id)
        }, [])
      

      此函数调用并更新 count 的值。

      setInterval 函数设置自动再次调用的时间间隔

      我希望你能清楚这一点。

      【讨论】:

        猜你喜欢
        • 2020-10-26
        • 2015-02-07
        • 1970-01-01
        • 2014-10-07
        • 1970-01-01
        • 1970-01-01
        • 2020-06-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多