无法读取未定义的属性"map",为什么? [英] Cannot read property 'map' of undefined, why?
问题描述
这是我的App.js文件.我正在尝试使用fetch()获取数据我想念什么?将错误作为TypeError:无法读取属性未定义的地图".怎么了?怎么得到结果?
我正在关注reactjs教程,但一直遇到问题将值从一个组件的状态传递到另一个组件时成分.抛出错误无法读取未定义的属性'map'"当执行CommentList组件中的map函数时.什么会导致道具在获取数据时变得不确定?我也尝试放置调试器,为什么它不在fetch调用中?
This is my App.js file. I am trying to fetch data using fetch()
What am I missing? Getting Error as TypeError: Cannot read property
map of undefined". What is wrong? How do I get the result?
I'm following the reactjs tutorial, and I keep running into an issue
when passing the value from the state of one component into another
component. The error 'Cannot read property 'map' of undefined' is thrown
when the map function in the CommentList component is executed. What
would cause the prop to become undefined when fetching data? I also
tried putting debugger, why it is not going inside the fetch call?
import React, { Component } from 'react';
import UsingFetch from './UsingFetch';
class App extends Component {
constructor(props){
super(props);
this.state = {
companyList:[]
};
}
componentDidMount(){
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => { res.json() })
.then(
res => {
this.setState({
companyList : res
});
},
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
return (
<div className="App">
1) DataGrid
<UsingFetch datasource = {this.state.companyList}/>
</div>
);
}
}
export default App;
这是我的UsingFetch.js文件
This is my UsingFetch.js File
class UsingFetch extends Component{
constructor(){
super();
this.state = {
isLoaded:false,
}
}
render() {
return (
<div>
{this.props.datasource.map(item =>
<div>
{item.name}
</div>
)}
</div>
)
}
}
这是我的App.js和UsingFetch.js文件.我正在尝试获取数据使用fetch(),我缺少什么?错误提示为:
This is my App.js and UsingFetch.js file. I am trying to fetch data using fetch(), What am I missing? Getting Error as:
TypeError:无法读取未定义的属性映射"
TypeError: Cannot read property map of undefined"
怎么了?我如何得到结果?
What is wrong? How do I get the result?
推荐答案
由于您没有从第一个 then
块返回任何内容.因此,第二个 then
块中的 res
是 undefined
.您应该在
Since you are not returning anything from first then
block. So res
in second then
block is undefined
. you should use return
in
then(res => { res.json() })
更改为
then(res => res.json())
或
then(res => { return res.json() })
这篇关于无法读取未定义的属性"map",为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!