我正在关注 ReactJS AJAX 和 API 教程。我在 Spring 中编写了一个简单的 API,然后在 http://localhost:8080
中使用该 API 的 React 组件。 API 目前返回一个包含两个项目的列表,如下所示:
[
{brand:"Asus", make:"AAA"},
{brand:"Acer", make:"BBB"}
]
这是我的组件的样子:
import React from 'react';
import ReactDOM from 'react-dom';
import { environment } from '../environment/environment';
export class ComputerList extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: [
{brand: null, make: null}
]
};
}
componentDidMount() {
fetch("http://localhost:8080/computers")
.then(res => res.json())
.then(
(result) => {
// correctly displays the results
console.log(result);
this.setState({
isLoaded: true,
items: result.items
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if(error) {
return(<div>Error: {error.message}</div>);
}
else if(!isLoaded) {
return(<div>Loading...</div>);
}
else if(items) {
console.log(items);
// error here: cannot read property "map" of undefined
// because this.state.items is undefined somehow?
return(
<ul>
{items.map(item => (
<li key={item.make}>{item.brand} {item.make}</li>
))}
</ul>
);
}
}
}
在第 24 行,成功检索并记录了结果。
但是在第 54 行,当我尝试将每个结果映射到 <li>
项时,抛出 TypeError
因为 items
未定义-isaaf4我通过在第 12 行初始化 items
并在第 48 行检查 items
来跟踪 类似问题 的答案,但无济于事。
我怎样才能解决这个问题?
原文由 Jason 发布,翻译遵循 CC BY-SA 4.0 许可协议
感谢@DacreDenny 的建议 :)
第 27 行:
items: result.items
。此行期望响应包含名为“items”的对象。但是我的 API 只返回一个对象数组。所以我将行更改为
第 27 行到:
items: result
。这会将整个数组保存到state.items
。然后它可以被正确地映射和渲染。