我在将JSON加载到React组件时遇到问题,该组件将提供由SurveyJS驱动的调查。
当我将调查数据定义为组件文件中的对象时,一切正常。当我从API(AWS-Lambda)获取JSON并将其置于状态时,它不起作用。
我都在控制台上记录日志,而且我无法检测到状态值与内联定义的值之间的任何差异,这是一个难题! SurveyJS错误消息为调查中没有可见的页面或问题。
我在处理状态或JSON对象时出了什么问题?
import React, { Component } from "react";
import * as Survey from "survey-react";
import "survey-react/survey.css";
import "survey-react/modern.css"
import { API } from "aws-amplify";
export default class SimpleSurvey extends Component {
constructor(props) {
super(props);
this.state = {
survey: {},
};
}
async componentDidMount() {
try {
let querystring = {'queryStringParameters':{'surveyId':this.props.surveyId}}
const surveyjson = await this.getSurvey(querystring);
this.setState({ survey: surveyjson});
} catch (e) {
alert(e);
}
}
getSurvey(querystring) {
return API.get("survey", "/survey", querystring);
}
simpleone = {"pages": [{"name": "page1","elements": [{"type": "text","name": "question1"}]}]}
render() {
console.log('simpleone object', this.simpleone)
console.log('state object', this.state.survey)
console.log('both obj the same?', this.simpleone === this.state.survey)
console.log('simpleone string', JSON.stringify(this.simpleone))
console.log('state string', JSON.stringify(this.state.survey))
console.log('both string the same?', JSON.stringify(this.simpleone)===JSON.stringify(this.state.survey))
// issue: model works if use this.simpleone defined above; does not work if use this.state.survey set from API
var model = new Survey.Model(this.simpleone);
return (<Survey.Survey model={model}/>);
}
}
这是带有simpleone对象和状态的console.log ...
是@saglamcem-问题在尝试创建模型之前没有等待异步]
已更改渲染功能,以等待在调用新Survey.Model之前使用API中的JSON填充状态,>
export default class SimpleSurvey extends Component {
constructor(props) {
super(props);
this.state = {
survey: null,
};
}
async componentDidMount() {
try {
let querystring = {'queryStringParameters':{'surveyId':this.props.surveyId}}
const surveyjson = await this.getSurvey(querystring);
this.setState({ survey: surveyjson});
} catch (e) {
alert(e);
}
}
getSurvey(querystring) {
return API.get("survey", "/survey", querystring);
}
getModel(json){
var model = new Survey.Model(json);
return (<Survey.Survey model={model} onComplete={this.onComplete}/>);
}
onComplete(survey, options) {
console.log("Survey results: " + JSON.stringify(survey.data));
}
render() {
return(
<div>
{this.state.survey ? this.getModel(this.state.survey) : null}
</div>
)
}
}