【问题标题】:Access value from Promise for HTML Element从 Promise 访问 HTML 元素的值
【发布时间】:2021-03-14 04:40:48
【问题描述】:

我是 React 和 javascript 的新手,需要一些帮助。我正在使用一个返回包含接口的 Promise 的函数。我想访问接口中的变量并将其应用到<dl><dt>{//string variable}</dt></dl>

问题是我只得到一个 Promise 对象,我需要它作为一个字符串。我该怎么做?

这是我获取 Promise 对象并使用它的异步函数:

async function getName() {
  const res = await getNamePromise(); // type: Promise<Interface>
  console.log(res.name);
}

export function userInfo(){
return(
<dl>
    <dd>{// need a string variable}</dd>
</dl>
);
} 

什么时候这样写: getName().then((name) =&gt; console.log(name)); 名称是一个字符串。但是如何将其存储为字符串变量并使用它呢?

【问题讨论】:

    标签: javascript reactjs typescript promise async-await


    【解决方案1】:

    你正在使用React,所以你应该将api调用和html标签放入一个react组件中,并将api响应数据与组件状态一起保存以触发重新渲染,试试这个:

    function NameComponent() {
      React.useEffect(() => {
        async function getName() {
          const res = await getNamePromise(); // type: Promise<Interface>
          setName(res.name)
        }
    
        getName()
      }, [])
    
      React.useEffect(() => {
        async function getPhoto() {
          const res = await getPhotoPromise(); // type: Promise<Interface>
          setPhoto(res.photo)
        }
    
        getPhoto()
      }, [])
    
      const [name, setName] = React.useState()
      const [photo, setPhoto] = React.useState()
    
      if (!name || !photo) {
        return <div>Loading...</div>
      }
    
      return(
        <dl>
          <dd>{name}</dd>
          <dd>{photo}</dd>
        </dl>
      );
    } 
    

    【讨论】:

    • 这成功了!但是如果我想获取多个变量并将它们用作字符串,是否需要为每个变量创建一个新的组件?
    • 我更新了我的答案,你也可以把它们放在同一个组件中,当组件太大时,考虑拆分成其他组件
    猜你喜欢
    • 2013-04-24
    • 2014-09-19
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 2018-08-03
    • 2015-11-23
    • 1970-01-01
    相关资源
    最近更新 更多