React如何从api渲染异步数据? [英] React how to render async data from api?

查看:43
本文介绍了React如何从api渲染异步数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是preact(react的轻型版本),但是语法几乎相同.从promise结果设置状态后,我遇到了显示已验证的问题.这是我的容器组件:

I am using preact(light version of react) but syntax is almost the same. I am having an issue displaying verified after setting state from promise result. This is my container component:

import { h, Component } from "preact";
import { VerifierService } from "services/verifierService";
var CONFIG = require("Config");

//import * as styles from './profile.css';

interface PassportProps { token?: string; path?: string }
interface PassportState { appId?: string; verified?: boolean }

export default class Passport extends Component<PassportProps, PassportState> {
  constructor(props) {
    super(props);

    this.state = { appId: CONFIG.Settings.AppId };
  }

  async componentDidMount() {
    console.log("cdm: " + this.props.token);

    if (this.props.token != undefined) {
      await VerifierService.post({ token: this.props.token })
        .then(data => {
          this.setState({ verified: data.result });
          console.log(JSON.stringify(data, null, 4));
        })
        .catch(error => console.log(error));
    }
  }

  render() {
    return <div>Test: {this.state.verified}</div>;
  }
}

我可以在promise结果中看到console.log为true,但是我无法在视图中显示它.

I can see console.log as true inside of promise result, but i can't display it in view.

推荐答案

您的 console.log 中的 data true ,因此 data.result 将为您提供 undefined .尝试仅在 setState 中设置 data .

Your data in your console.log is true, so therefor data.result will give you undefined. Try to just set the data in setState.

await VerifierService.post({ token: this.props.token })
  .then(data => {
    this.setState({ verified: data });
    console.log(JSON.stringify(data, null, 4));
  })
  .catch(error => console.log(error));

这篇关于React如何从api渲染异步数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆