componentDidMount和XMLHttpRequest两次使用无效的JSON加载数据

时间:2015-11-11 13:33:51

标签: javascript ajax node.js reactjs xmlhttprequest

我正在使用简单的快速静态服务器来管理静态文件。

app.use(express.static(path.join(__dirname, 'public')));

这是 webpack.config.js 文件

const webpack = require('webpack');
const path = require('path');

module.exports = {
  entry: './src/app.js',
  output: {
    path: path.join(__dirname, 'public'),
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin()    
  ],
  module: {
    loaders: [{
      test: /\.js$/,
      loader: 'babel',
      query: {
        presets: ['es2015','react']
      }
    }]
  },
  devtool: 'eval-source-map'
}

这是我的问题反应组件 question.js

import React from 'react';
import ReactDOM from 'react-dom';

const stackAddress = 'https://api.stackexchange.com/2.1/questions?site=stackoverflow';

class Question extends React.Component{
  constructor(){
    super();
    this.loadDataFromStack = this.loadDataFromStack.bind(this);
    this.state = {
      itemList: []
    }
  }

  componentDidMount() {
    console.log('Load data from Stack');
    this.loadDataFromStack()
  }

  loadDataFromStack(){
    var request = new XMLHttpRequest();
    request.open('GET',stackAddress, true);
    request.onreadystatechange = () => {
      console.log(JSON.parse(request.responseText));
    };
    request.send()
  }
  render(){
    return <div>
      <h1>Questions</h1>
      <ul></ul>
    </div>
  }
}

export default Question

当我运行服务器时,我得到了next error,而且我注意到我在屏幕上看到了两次请求。

但如果我使用 jQuery.get jQuery.ajax 方法而不是效果正常

有人可以建议问题出在哪里吗?

提前致谢。

1 个答案:

答案 0 :(得分:0)

我并非100%确定这可能是问题,但通常情况下,在执行XMLHttpRequest时,您应该在调用open之前设置处理程序。所以我会这样试试:

&#13;
&#13;
loadDataFromStack(){
  var request = new XMLHttpRequest();
  request.onreadystatechange = () => {
    if (request.readyState == 4 && request.status == 200) {
       console.log(JSON.parse(request.responseText));
    }
  };
  request.open('GET',stackAddress, true);
  request.send()
}
&#13;
&#13;
&#13;

注意request.onreadystatechange = ()之前应调用request.open('GET',stackAddress, true);