首页 > 解决方案 > 我如何在 React 中返回一个数字?

问题描述

在反应中,我想做的就是查找并返回一个数字。我有:

  getVAL = async ()  => {
    const pathParam = this.props.match.params.myVal;
    const url = "get-myVal?myVal=" + pathParam;
    const response = await this._axios.get(url);
    const intmyVal = Number(response.data);
    return   Number (intmyVal)
  };

我用这个:

 myVal=this.getVAL();

但是当我渲染...

  myVal={this.myVal}

Type 'Promise<number>' is not assignable to type 'number'.对这个奇怪的世界完全陌生,所以任何指针都值得赞赏。

编辑:在 jonrsharpe 的帮助下(任何错误,我的),我现在有:

myIdPromise=this.getID();

myIdPromise.then(don't know what to put here to just get a number {
   ...
})

标签: reactjstypescript

解决方案


这有效:

async getIDPromise(): Promise<Number> {
...
  return   intmyVal
}

async getID(): Promise<Number> {

  const value = await this.getIDPromise()

推荐阅读