【问题标题】:React how to render async data from api?React 如何从 api 呈现异步数据?
【发布时间】:2018-06-30 16:41:41
【问题描述】:

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

【问题讨论】:

  • console.log 中的数据是什么样的?
  • "true" 作为布尔值

标签: javascript reactjs preact


【解决方案1】:

您的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));

【讨论】:

  • 实际上数据是真实的,但由于模型结果是布尔值,所以它与我的模型不匹配,必须修复它。你能确认生命周期没问题吗?
  • @AmelSalibasic 是的,您的代码看起来不错。由于您使用的是async/await,如果您认为这更具可读性,您也可以写const data = await VerifierService.post({ token: this.props.token }); this.setState({ verified: data });
  • 布尔值也无法渲染,我们必须将其转换为字符串
猜你喜欢
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-26
  • 2021-01-10
相关资源
最近更新 更多