React 如何从 api 渲染异步数据?

React how to render async data from api?

我正在使用 preact(react 的轻型版本),但语法几乎相同。在根据承诺结果设置状态后,我在显示已验证时遇到问题。这是我的容器组件:

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 为真,但我无法在视图中显示它。

你的 data 在你的 console.log 中是 true,因此 data.result 会给你 undefined。尝试在 setState.

中设置 data
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));