Axios 加载 API,之后无法在 DOM 中引用 API,"TypeError: this.state.products.map is not a function"



我正在使用Axios加载本地API。在.then上,如果我console.log结果,我会在控制台中得到很好的结果。

然后,我将其分配到"products"名称下的状态。在DOM中,如果我尝试引用它,我会得到错误:

TypeError: this.state.products.map is not a function

这有什么原因?我将API调用封装在ComponentWillMount((中,但它仍然不起作用。

这是我的代码:

App.js

import axios from "axios"
import React from "react"
// const api = axios.create({
//   baseURL: `http://localhost/api/`,
// })
class App extends React.Component {
constructor() {
super()
this.state = {
products: [],
}
}
componentDidMount() {
axios.get("http://localhost/api/").then((res) => {
console.log(res.data)
this.setState({ products: res.data })
})
}
render() {
return (
<div>
{this.state.products.map((product) => (
<div>
<h1>{product.id}</h1>
</div>
))}
</div>
)
}
}
export default App

验证res.data:mb中的内容——它是一个JSON字符串,您需要首先解析它,或者它是object,但它应该是数组。

最新更新