簡體   English   中英

React如何從api渲染異步數據?

[英]React how to render async data from api?

我正在使用preact(react的輕量級版本),但是語法幾乎相同。 從promise結果設置狀態后,我遇到了顯示已驗證的問題。 這是我的容器組件:

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

我可以看到console.log在promise結果內是真實的,但是我無法在視圖中顯示它。

您在console.log datatrue ,因此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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM