【问题标题】:Javascript return values返回值
【发布时间】:2022-12-19 20:16:01
【问题描述】:

我有一个返回函数结果的助手:

        TimerCalc =()=>{    
           (...other calculations...)
           const formatedTime = () => {
           return [pad(parseInt(seconds / 60)), pad(seconds % 60)].join(':')
           }
    
        return formatedTime()
        }

在父组件中,我收到这样的值:

  const counter = <TimerCalc resetTimer={reset} runTimer={startStopTimer} />

...以所需格式正确返回格式化时间,如“00:00”

但我现在需要与格式化时间一起返回第二个值,所以我正在尝试:

return [formatedTime(), secondValue]

希望像 counter[0] 这样的东西能给我父组件中的第一个值和 conter[1] 第二个值。但事实并非如此。

问题是我不知道如何获取这两个值,因为执行 console.log({counter}) 会向我显示一个没有值的对象:

Object {
  "counter": Object {
    "$$typeof": Symbol(react.element),
    "_owner": FiberNode {
      "tag": 0,
      "key": null,
      "type": [Function Today],
    },
    "_store": Object {},
    "key": null,
    "props": Object {
      "resetTimer": false,
      "runTimer": false,
    },
    "ref": null,
    "type": [Function TimerCalc],
  },
}

谁能帮忙,告诉我如何正确执行此操作并访问父组件中的两个值?谢谢!

【问题讨论】:

  • 组件不是普通对象,不应该那样使用
  • JSX 元素通常用于表示将出现在 UI 中的内容,如果您只需要将字符串/数组分配给变量,这是否需要在 JSX 中?它不能是一个常规函数吗? (您以后始终可以在 UI 中单独使用该值)

标签: javascript


【解决方案1】:

貌似你用的是react,所以你无法通过这种方式获取组件的返回值,实际上我们使用custom hook来满足这种需求

像这样 :

const useTimerCalc =({resetTimer,startStopTimer})=>{
  (...other calculations...)
  const formatedTime = () => {
    return [pad(parseInt(seconds / 60)), pad(seconds % 60)].join(':')
  }

  return [formatedTime(), secondValue]
}

并在其他组件中以这种方式使用它:

  const [formatedTime,secondValue] = useTimerCalc({
    resetTimer:reset,
    startStopTimer:startStopTimer
  })

【讨论】:

    猜你喜欢
    • 2011-02-24
    • 1970-01-01
    • 2014-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-19
    相关资源
    最近更新 更多