我是 React 新手,我正在尝试构建(目前)一个简单的应用程序,它允许您在交易列表中搜索名称并将交易详细信息返回给您。到目前为止,我一直在努力处理 API 请求,并且不断遇到错误。我正在使用 superagent 进行 API 调用
import React, {Component } from 'react';
import Request from 'superagent'
import './App.css';
class App extends Component {
constructor() {
super();
this.state = {};
}
componentWillMount() {
var url = 'https://api.myjson.com/bins/2dorw';
Request.get(url).then((response) => {
this.setState({
items: response.body.items,
});
});
}
render() {
var names = this.state.items.map((name, index) => {
<div>
<li key={index}> {this.state.items.merchant.name } </li>
</div>
});
return (
<div className="App">
{names}
</div>
);
}
}
export default App;
我什至无法使这个简单的 API 调用正常工作,只能显示来自 API 端点的名称。这种情况已经持续了一天左右,通常我会得到对象 null、未定义和类型错误。
Uncaught (in promise) TypeError: Cannot read property '_currentElement' of null(…)
App.js:64 Uncaught TypeError: Cannot read property 'map' of undefined
我已尝试遵循教程,但无法找到适合我的情况的教程,因此我无法专注于 API 调用。
更新
更改为 componentDidMount() 后,添加 isFetching 并将项目设置到 setState 中的数组(正如两个答案所建议的那样),我现在得到一个
Uncaught (in promise) TypeError: Cannot read property 'name' of undefined
最佳答案
使用 componentWillMount()
处于生命周期的早期。等到使用 componentDidMount()
挂载它,这应该有助于解决抛出的第一个错误。
当items
尚未显示时,第二个错误来自this.state.items.map
。我还建议添加一个 isFetching
状态,以检查数据是否已显示。:
class App extends Component {
constructor() {
super();
this.state = {
isFetching: true
};
}
componentDidMount() {
var url = 'https://api.myjson.com/bins/2dorw';
Request.get(url).then((response) => {
this.setState({
items: response.body.items,
isFetching: false
});
});
}
render() {
if (this.state.isFetching) return null;
var names = this.state.items.map((item, index) => {
<div>
<li key={index}> {item.merchant.name} </li>
</div >
});
return (
<div className="App">
{names}
</div>
);
}
}
export default App;
更新
添加了一个轻微的更改 - 看起来您的 map 功能也有点关闭。很难说你到底在寻找什么,因为我不确切知道数据结构。
你有
var names = this.state.items.map((name, index) => {
<div>
<li key={index}> {this.state.items.merchant.name } </li>
</div>
});
将 name
作为第一个参数传递,这是整个项目。然后你再次调用 this.state - 你不需要这样做。我认为这也是一些未定义
问题的根源。
关于javascript - React API调用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40243547/