TypeError:无法读取未定义的属性"map"-如何访问本地json API中的数组 [英] TypeError: Cannot read property 'map' of undefined - how to access an array in a local json API
问题描述
我能够使用提取功能在本地导入api JSON,该api可在此网址中找到如果要查看它.
I was able to import an api JSON locally using fetch, the api is available in this url if you want to view it.
问题如下,通过状态searchString时,出现以下错误:
The problem is the following, when passing the state searchString I get the following error:
"TypeError:无法读取属性"映射未定义"
'TypeError: Can not read property' map 'of undefined'
我认为这是因为我正在导入完整的json对象,而我只需要访问关键结果.
I believe that is because I am importing the complete json object, whereas I need to access only key results.
File App.js
class App extends Component {
constructor(props) {
super(props);
this.state = {
searchString: []
};
}
componentDidMount() {
fetch('./recipes.json')
.then(response => response.json())
.then(json => console.log(json ))
.then(json => this.setState({ searchString: json }));
}
render() {
return (
<div className="App">
<Navbar />
<div className="container mt-10">
<div className="row">
<RecipeItem list={this.state.searchString}/>
</div>
</div>
</div>
);
}
}
File RecipeItem.js
const RecipeList = ({ searchString }) => {
<div>
<img className="card-img-top img-fluid" src={searchString.href} alt={searchString.title} />
<div className="card-body">
<h5 className="card-title">{searchString.title}</h5>
<p className="card-text">
<strong>Ingredients: </strong>{searchString.ingredients}
</p>
</div>
</div>
}
const RecipeItem = (props) => {
return (
<div className="col-sm-3 mt-4">
<div className="card">
{props.list.map((searchString, index) =>
<RecipeList searchString = {searchString} key={index} />
)}
</div>
</div>
)
}
推荐答案
RecipeItem
组件在初始安装时没有数据,因为您正在执行访存调用.因此,这就是您收到错误的原因.
RecipeItem
component doesn't have the data when it's initially mounted, since you're doing a fetch call. So that's why you receive the error.
您可以添加一个简单的检查,看看是否有数据,然后执行map/filter/或其他任何操作:
You can add a simple check if you have data and then do the map/filter/ or anything else:
{props.list && props.list.map((searchString, index) =>
<RecipeList searchString = {searchString} key={index} />
)}
这篇关于TypeError:无法读取未定义的属性"map"-如何访问本地json API中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!