简体   繁体   English

从 HTML 元素的 Promise 访问值

[英]Access value from Promise for HTML Element

I'm new to React and javascript and need some help.我是 React 和 javascript 的新手,需要一些帮助。 I'm using a function that returns a Promise including an interface.我正在使用 function 返回一个 Promise 包括一个接口。 I want to access the variable in the Interface and apply it in <dl><dt>{//string variable}</dt></dl> .我想访问接口中的变量并将其应用于<dl><dt>{//string variable}</dt></dl>

The problem is that I'm only getting a Promise object, and I need it as a string.问题是我只得到一个 Promise object,我需要它作为字符串。 How can I do this?我怎样才能做到这一点?

This is my async function for getting the Promise object and using it:这是我的异步 function 用于获取 Promise object 并使用它:

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>
);
} 

When is write it like this: getName().then((name) => console.log(name));什么时候这样写: getName().then((name) => console.log(name)); name is a string.名称是一个字符串。 But how can I store this as a string variable and use it?但是如何将其存储为字符串变量并使用它呢?

You're using React, so you should put api call and html tag into a react component, and save the api response data with component state to trigger re-render, try this: You're using React, so you should put api call and html tag into a react component, and save the api response data with component state to trigger re-render, try this:

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>
  );
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM