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

时间:2018-06-30 16:41:42

标签: javascript reactjs preact

我使用的是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为true,但是我无法在视图中显示它。

1 个答案:

答案 0 :(得分:2)

data中的console.logtrue,因此data.result将给您undefined。尝试仅在data中设置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));