reactjs - 如何修复 Reactjs 中的“items.map 未定义”错误
问题描述
我只是关于 reactjs 的新开发人员
我正在尝试映射数据。我正在关注 reactjs 教程,这是我的结果,但我尝试并再次尝试它是否不起作用。我该如何解决??
class App extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
// API from reqres
fetch("https://reqres.in/api/users/2")
.then(res => res.json())
.then(
(result) => {
console.log(result.data);
this.setState({
isLoaded: true,
items: result.data
});
},
(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 {
return (
<div>
//this is the problem
{items.map(item=> {
return <div>
<p>{item.id}</p>
</div>
})}
</div>
);
}
}
}
export default App;
请帮助我,我只想查看我的数据:(
在我将 fetch 更改为 Axios 后,我遇到了同样的问题??
Axios({
method:"GET",
url:"https://reqres.in/api/users"
}).then(res => {
this.setState({
isLoaded:true,
items: res.data
})
console.log(res.data)
}).catch(err => {
console.log(err)
})
解决方案
您可以通过为项目提供默认值来解决此问题:
const { error, isLoaded, items = [] } = this.state;
推荐阅读
- python - Python,codecs.open() 给出 [Errno 2] “没有这样的文件或目录”作为输出,即使文件存在
- reactjs - React - 材质 UI - BottomNavigationAction - 活动子路线
- java - javafx 用户界面应用程序无法访问 ArrayList 中的所有值
- vue.js - 我正在使用'sortablejs'库是否可以选择动态元素,其值在点击事件时发生变化
- kubernetes - Kubernetes - 授予对匹配前缀或正则表达式的所有命名空间的完全访问权限
- java - 在 Android 中使用外部非 Android Java 库:找不到 .so 文件等
- html - 如何在 HTML 正文中设置固定位置并冻结我的面包屑?
- sql - SELECT INTO,其中源数据位于目标表以外的其他数据库中
- python - python 获取数组中的excel工作表名称,并将其置于条件中
- angular - 启用“groupIncludeTotalFooter”的 Ag-Grid 在数据透视图中创建一个空数据列