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