从api反应初始化状态,状态未定义

时间:2018-03-14 01:03:20

标签: javascript reactjs api initialization state

import request from 'request';
var pdfAnnotations;
request('GET', url_ws).done((res) => {
 if (res.statusCode==200) {
  parseString(res.getBody(),{explicitArray:false}, function (err, result) {
    pdfAnnotations=result['root']['element'];
    console.log(pdfAnnotations);// it's OK values
  });
 }
});
console.log(pdfAnnotations);//display "undefined"//first

class App extends Component<Props, State> {
  state = {
    info: pdfAnnotations//is null
  };
  state: State;

我需要从web api数据加载状态,状态是'未定义&#39;,是可能同步还是其他方式???

1 个答案:

答案 0 :(得分:0)

您可以将信息的初始值设置为null,然后从服务器加载数据并调用this.setState以设置componentDidMount

中的状态
import request from 'request';

class App extends React.Component {
  constructor(props) {
    this.state = {
      info: null
    }
  }
  componentDidMount() {
    request('GET', url_ws).done((res) => {
      if (res.statusCode == 200) {
        parseString(res.getBody(), { explicitArray: false }, (err, result) => {
          const pdfAnnotations = result['root']['element'];
          this.setState({ info: pdfAnnotations });
        });
      }
    });
  }
}