【发布时间】:2019-03-02 21:14:12
【问题描述】:
我正在关注 ReactJS AJAX and APIs tutorial。我在 Spring 中编写了一个简单的 API,然后在 http://localhost:8080 处编写了一个 React 组件来使用该 API。 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 不知何故未定义?我通过在第 12 行初始化 items 并在第 48 行检查 items 来跟踪similar question 的答案,但无济于事。
我该如何解决这个问题?
【问题讨论】:
标签: javascript reactjs