【发布时间】:2020-03-26 22:36:45
【问题描述】:
woocommerce 商店的结束应用程序,但我在渲染数组的第一个图像时遇到问题 当我 console.log(images.src) 我看到图像的 url 列表,但在 img src= 它返回: TypeError: Cannot read property 'src' of undefined 我将非常感谢帮助我正确映射图像。 这是我的代码:
class App extends React.Component {
constructor(props) {
super(props);
this.getPosts = this.getPosts.bind(this);
this.state = {
posts : [],
images: []
};
}
getPosts = async () => {
let res = await api.get("products", {
per_page: 20,
})
let { data } = await res;
this.setState({ posts: data });
}
componentDidMount = async () => {
await this.getPosts();
};
render() {
const { posts } = this.state;
const { images } = this.state
return(
<div>
<Head>
<title>Онлайн магазин KIKI.BG</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<React.Fragment >
{posts.map((posts, index ) => {
{
posts.images.map((images, subindex) =>
console.log(images.src),
<img src={images[0].src} />
)}
return (
<div>
<h1>{posts.name}</h1>
<h2>{posts.price}</h2>
</div>
)})}
</React.Fragment>
</div>
)
}
}
export default App;
【问题讨论】:
-
我认为您应该从 posts.images.map() 中删除
console.log(images.src)。它会将您的数组映射到未定义的数组:) -
发布posts.images里面包含什么
-
是的,我只是测试是否记录了图像 url 端点,并且 console.log 返回正确的端点,例如 xxxxxx/wp-content/uploads/2019/12/570-496-max.jpg ,但 返回TypeError:无法读取未定义的属性“src”
标签: reactjs