我正在从wordpress api获取数据。登录控制台时,我看到了数据数组。在映射数据时,出现错误消息“#myStateName.map不是函数”。
我已经去过ReactJS.org,CSS Tricks甚至Stack Overflow来寻找解决方案,但似乎没有任何效果
class WPHome extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
details: []
};
}
componentDidMount() {
fetch(API_URL)
.then(res => res.json())
.then(
(result) => {
console.log(result['0'])
this.setState({
isLoaded: true,
details: [result]
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, details } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div>
{details.map(item => (
<div key={item.id}>
<p>{item.id}</p>
<div>
<img src={item._embedded['wp:featuredmedia']['0'].source_url} alt={item.id} />
</div>
<p>{item.content}</p>
<hr />
</div>
))}
</div>
);
}
}
我希望我的数据传递到HTML块中,但是会抛出错误。
我终于弄明白了。虽然必须使用Axios,但它确实有效。
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
details: []
};
}
componentDidMount(){
axios
.get(API_URL)
.then(response => response.data.map(detail => ({
image: `${detail._embedded['wp:featuredmedia']['0'].source_url}`,
content: `${detail.content.rendered}`,
id: `${detail.id}`
}))
)
.then(details => {
this.setState({
details,
isLoading: false
});
})
.catch(error => this.setState({ error, isLoading: false }));
}
render() {
const { isLoading, details } = this.state;
return (
<React.Fragment>
{!isLoading ? (
details.map(detail => {
const { id, content, image } = detail;
return (
<div key={id}>
<p>{content}</p>
<div>
<img src={image} alt={id} />
</div>
<p>{content}</p>
<hr />
</div>
);
})
) : (
<p>Loading</p>
)
}
</React.Fragment>
)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句