Javascript 如何使用React从本地主机上运行的API加载和显示数据

Javascript 如何使用React从本地主机上运行的API加载和显示数据,javascript,reactjs,Javascript,Reactjs,我收到一个错误“app.js:16 Uncaught(in promise)TypeError:无法使用下面的代码读取未定义的属性“0”。 我试图使用React来显示在本地主机上运行的DrupalAPI中的数据。 在React应用程序中,我使用一个简单的HTTP服务器(python-msimplehttpserver)来防止XMLHttpRequest错误,并且在我的API上启用了CORS。我使用的不是jQuery,而是Axios 我无法让index.html显示文本“Event!”以外的任何内

我收到一个错误“app.js:16 Uncaught(in promise)TypeError:无法使用下面的代码读取未定义的属性“0”。

我试图使用React来显示在本地主机上运行的DrupalAPI中的数据。 在React应用程序中,我使用一个简单的HTTP服务器(python-msimplehttpserver)来防止XMLHttpRequest错误,并且在我的API上启用了CORS。我使用的不是jQuery,而是Axios

我无法让index.html显示文本“Event!”以外的任何内容,我做错了什么?这是我的app.js

class App extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      title: ''
    }
  }

  componentDidMount() {
    var th = this;
    this.serverRequest = 
      axios.get(this.props.source)
        .then(function(event) {    
          th.setState({
            title: event.title[0].value
          });
        })
  }

  componentWillUnmount() {
    this.serverRequest.abort();
  }

  render() {
    return (
      <div>
        <h1>Event!</h1>
        <h2>{this.state.title}</h2>
      </div>
    );
  }
}

ReactDOM.render(
    <App source="http://localhost:8888/drupal/api/events" />,
     document.getElementById('container')
);
然后我在控制台上得到以下信息:


Axios承诺在成功时生成一个响应对象,该对象具有包含响应主体的
数据属性;似乎您正在尝试访问响应对象的[0]属性,而不是其
数据的[0]属性,该属性将是您期望的数组。此外,在访问结构时似乎还出现了其他错误。试试这个或类似的方法:

axios.get(this.props.source).then(event => {    
  th.setState({
    title: event.data[0].title[0].value
  });
});

专业提示:由于您已经在使用ES6类,请开始使用ES6 arrow语法编写函数:
(event)=>this.setState({title:event.title[0].value})
arrow函数以词汇形式绑定
this
,这意味着您不再需要执行
var th=this
。同样,开始使用
let
const
而不是
var
。你能检查一下你的控制台,看看页面是否正在加载本地文件吗?快速阅读React/JSX看起来不错,所以我猜这是AJAX请求的问题。谢谢,我现在用控制台检查了一下,它正在加载本地文件。在浏览器上,我可以看到标记内的文本“Event!”,但没有其他内容。我收到一个错误“app.js:16 Uncaught(in promise)TypeError:无法读取未定义的属性“0”。这意味着您的
事件
响应中的
title
字段不存在。验证终结点返回的数据。
componentDidMount() {
    var th = this;
    this.serverRequest =     axios.get(this.props.source).then(function(result) {    
           console.log(result);
    })
}
axios.get(this.props.source).then(event => {    
  th.setState({
    title: event.data[0].title[0].value
  });
});