无法从我的反应应用程序中的调查 js 获取 Json 输出

问题描述

我正在我的反应应用程序中实施调查反应:

import React,{Component} from 'react';
import "survey-react/survey.css";
import * as Survey from 'survey-react';

class App extends Component {
  constructor(props){
    super(props);
    this.state ={

    }
    this.onCompleteComponent = this.onCompleteComponent.bind(this)
  }

  onCompleteComponent = () =>{
    this.setState({
      isCompleted: true
    })
  }

  render() {
    Survey
    .StylesManager
    .applyTheme("");

    var json = {
      "title": "Simple Survey","logoWidth": 60,"logoHeight": 60,"questions": [
        {
          "type": "dropdown","name": "person","title": "Choice","hasOther": true,"isrequired": true,"choices": ["A","B","C"]
      },{
              "name": "name","type": "text","title": "Your name:","isrequired": true
          },{
              "name": "I accept terms","type": "checkBox","choices": ["YES"]
          }
      ]
  };

 var model = new Survey.Model(json);

  var surveyRender = !this.state.isCompleted ?(
    <Survey.Survey
      model={model}
      showCompletedPage ={false}
      onComplete = {this.onCompleteComponent}
    />
  ) : null

  var isDone = this.state.isCompleted ?(
    <div>{JSON.stringify(model.data,null,3)}</div>
  ): null;

  return (
    <div className = "App">
      <div>
      {surveyRender}
      {isDone}
    </div>
    </div>
  );
}
}

export default App;

但我没有得到 Json 输出形式 isDone,我尝试按照此 https://surveyjs.io/Examples/Library/?id=survey-data&platform=Reactjs&theme=modern 进行操作,但此方法对我也不起作用,我应该更改代码以将调查结果作为 Json 对象获取

>

解决方法

您正在每次渲染时重新创建您的调查模型。这就是为什么它会在每次更改时重置。你需要做这样的事情:

import React,{Component} from 'react';
import "survey-react/survey.css";
import * as Survey from 'survey-react';

//Survey.StylesManager.applyTheme("");

  var json = {
      "title": "Simple Survey","logoWidth": 60,"logoHeight": 60,"questions": [
        {
          "type": "dropdown","name": "person","title": "Choice","hasOther": true,"isRequired": true,"choices": ["A","B","C"]
      },{
              "name": "name","type": "text","title": "Your name:","isRequired": true
          },{
              "name": "I accept terms","type": "checkbox","choices": ["YES"]
          }
      ]
  };

class App extends Component {
  constructor(props){
    super(props);

    this.model = new Survey.Model(json);
    this.state ={

    }
    this.onCompleteComponent = this.onCompleteComponent.bind(this)
  }

  onCompleteComponent = () =>{
    this.setState({
      isCompleted: true
    })
  }

  render() {

  var surveyRender = !this.state.isCompleted ?(
    <Survey.Survey
      model={this.model}
      showCompletedPage ={false}
      onComplete = {this.onCompleteComponent}
    />
  ) : null

  var isDone = this.state.isCompleted ?(
    <div>{JSON.stringify(model.data,null,3)}</div>
  ): null;

  return (
    <div className = "App">
      <div>
      {surveyRender}
      {isDone}
    </div>
    </div>
  );
}
}

export default App;