admin管理员组文章数量:1364573
I'm new to React and am trying to pull in some information from an API, but keep getting this error when using the .map function to pass the retrieved data into an array:
TypeError: items.map is not a function.
I'm not too familiar with JavaScript, so I don't fully understand what's going on here. I've included my code:
import React, { Component } from "react";
import "./App.css";
class App extends Component {
constructor() {
super();
this.state = {
items: [],
isLoaded: true
};
}
ponentDidMount() {
fetch("")
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json
});
});
}
render() {
var { items, isLoaded } = this.state;
var itemInfo = items.map(item => (
<div key={item.colors.id}>Hex:{item.colors.hex}</div>
));
if (!isLoaded) {
return <div>{itemInfo}</div>;
} else {
return <div className="App">{itemInfo}</div>;
}
}
}
export default App;
I'm new to React and am trying to pull in some information from an API, but keep getting this error when using the .map function to pass the retrieved data into an array:
TypeError: items.map is not a function.
I'm not too familiar with JavaScript, so I don't fully understand what's going on here. I've included my code:
import React, { Component } from "react";
import "./App.css";
class App extends Component {
constructor() {
super();
this.state = {
items: [],
isLoaded: true
};
}
ponentDidMount() {
fetch("http://www.colr/json/colors/random/7")
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json
});
});
}
render() {
var { items, isLoaded } = this.state;
var itemInfo = items.map(item => (
<div key={item.colors.id}>Hex:{item.colors.hex}</div>
));
if (!isLoaded) {
return <div>{itemInfo}</div>;
} else {
return <div className="App">{itemInfo}</div>;
}
}
}
export default App;
Share
Improve this question
edited Mar 10, 2019 at 16:08
halfer
20.4k19 gold badges109 silver badges202 bronze badges
asked Mar 9, 2019 at 20:50
Laurel LinkLaurel Link
3051 gold badge6 silver badges17 bronze badges
0
3 Answers
Reset to default 6Since the items
array in state is initially an empty array, you get this error when you change items
to something that is not an array.
Looking at the response from the API in your question, you will get an object from your JSON after you parse it. The array you want to use in the response is under the colors
property, and each element in this array has id
and hex
properties.
class App extends Component {
// ...
ponentDidMount() {
fetch("http://www.colr/json/colors/random/7")
.then(res => res.json())
.then(res => {
this.setState({
isLoaded: true,
items: res.colors
});
});
}
render() {
var { items, isLoaded } = this.state;
var itemInfo = items.map(item => <div key={item.id}>Hex:{item.hex}</div>);
// ...
}
}
Since you do not specify types for anything and it is not really clear (not even for a human-reader) that items
is an Array
, you should explicitly tell TypeScript to use it as an array.
You use Type Assertion for that purpose. Should be something like:
(items as Array<YourArrayElementType>).map(/* .. */);
However, as a good practice you should always explicitly specify the type of anything you declare. In this way anything within you codebase will be statically typed. For anything ing from the outside (such as API requests) you should cast the information to interface
s you define.
Tholle is absolutely correct as far as your specific problem... I would further clean up your code like so:
import React, { Component } from 'react';
class App extends Component {
state = { items: [], isLoading: true, error: null };
ponentDidMount() {
fetch('http://www.colr/json/colors/random/7')
.then(res => res.json())
.then(json => {
this.setState({
isLoading: false,
items: json.colors,
});
})
.catch(error =>
this.setState({ error: error.message, isLoading: false }),
);
}
renderColors = () => {
const { items, isLoading, error } = this.state;
if (error) {
return <div>{error}</div>;
}
if (isLoading) {
return <div>Loading...</div>;
}
return (
<div>
{items.map(item => (
<div key={item.id}>Hex: {item.hex}</div>
))}
</div>
);
};
render() {
return <div>{this.renderColors()}</div>;
}
}
export default App;
本文标签:
版权声明:本文标题:javascript - How to fix "TypeError: items.map is not a function" when working with React and APIs? - Stack Ove 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743705102a2524979.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论