【发布时间】:2019-08-21 09:53:55
【问题描述】:
我正在从 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 块中,但我得到了一个 error。
【问题讨论】:
-
能否分享API的响应
-
Object { id: 2, date: "2019-08-05T11:51:22", date_gmt: "2019-08-05T11:51:22", guid: {…}, modified: "2019-08-05T12:51:42", modified_gmt: "2019-08-05T12:51:42", slug: "home", status: "publish", type: "page", … } WPHome.jsx:21 -
您得到的响应结果是数组或对象,请使用console.log(typeof result)
-
能否附上
console.table(result)的浏览器控制台截图 -
上面写着“对象”
console.log(typeof result)
标签: javascript reactjs api