【问题标题】:React - pass prop that needs to be awaited forReact - 传递需要等待的道具
【发布时间】:2022-11-21 03:49:21
【问题描述】:

我试图从我的组件传递一个来自异步函数的道具。

我有以下代码:

export const Bar = (props: Props) => {
...
 const getValue = async () => {
    const { value } = await initValue();
    return  value;
  }
...
  return (
    <Foo value={getValue()}/> //Error in this line
}

TS 报错:

类型“Promise”缺少类型“Element”的以下属性:类型、道具、键 ts(2739) 块引用

我怎样才能做到这一点?

【问题讨论】:

  • 你能分享你打算用getValue()返回的值做什么吗?
  • 我认为您可以使用状态来存储值并将其传递给子项,或者使用它在子项中进行调用和 <Foo value={getValue}/> // getValue() => getValue

标签: javascript reactjs async-await react-props


【解决方案1】:

为什么要调用 getValue(),只需将其作为函数变量发送,然后在需要的地方调用它

   <Foo value={getValue}/> 

【讨论】:

    猜你喜欢
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 2018-11-20
    • 2018-05-22
    • 2020-11-17
    • 1970-01-01
    相关资源
    最近更新 更多