【问题标题】:React render array of images in array反应在数组中渲染图像数组
【发布时间】: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


【解决方案1】:
            {posts.map((posts, index ) => {
              { 
                posts.images.src.map((image, subindex) =>

                <img src={image.src} />
                )}
                return (
                  <div>
                       <h1>{posts.name}</h1>
                       <h2>{posts.price}</h2>
                 </div>  
                )
              })}

【讨论】:

  • 它返回
  • 做一个图像的控制台日志并在这里发布
  • 响应为:index.js:50 {id: 177401, date_created: "2019-12-02T14:41:29", date_created_gmt: "2019-12-02T10:41:29", date_modified: "2019-12-02T14:41:29", date_modified_gmt: "2019-12-02T10:41:29", ...} alt: "" date_created: "2019-12-02T14:41:29" date_created_gmt: " 2019-12-02T10:41:29" date_modified: "2019-12-02T14:41:29" date_modified_gmt: "2019-12-02T10:41:29" id: 177401 name: "570-570-max" src: "kiki.bg/wp-content/uploads/2019/12/570-570-max.jpg" proto: 对象
  • 返回 TypeError: Cannot read property 'map' of undefined
  • 这样做:console.log(JSON.stringify(posts.images)) 并在这里发布所有内容(我的意思是从头到尾)
【解决方案2】:

好吧,console.log(images.src) i see the list of urls of the images 没有任何意义。images 是数组。所以images[0] 应该是带有属性src 的数据的图像?顺便说一句,这段代码中的很多东西都是错误的。

  • 不要在构造函数中重新绑定getPosts 已经绑定的getPosts 函数(通过类属性)(getPosts)。顺便说一句,您根本不需要绑定,它不被称为回调。
  • 很奇怪,你在api.get() 之后调用await res ...不应该只是await api.get() 吗?另一个await 通常用于获取,当您执行await response.json() 之类的操作时。
  • componentDidMount 中不需要 async/await
  • 如果 getPosts 会抛出它会弄乱你的组件,最好处理 catch 中的错误并调用 props.onError(error) 例如
  • 您在地图中的元素上没有任何key 属性,这是错误的。您应该在其中放置一些唯一的 id(url fe?如果不相同,或者 id),以便正确地重新渲染组件。
  • 您的地图中有一些奇怪的括号问题...
  • 你不应该在一个页面上使用超过一个 h1 :-)
  • images.src 应该是字符串,而不是数组...
  • 不使用时为什么会有子索引和索引?
  • 为什么要存储未填充的图像?他们在得到响应吗?这也许就是你得到 TypeError 的原因!
  • 我会添加加载和无数据消息...

这将是我的代码:

import { Component, Fragment } from 'react';

class App extends Component {

  static defaultProps = {
    onError: console.error;
  };

  state = {
    posts: [],
    images: [],
    loading: false,
  };

  // This could be done with hooks much better tho...
  async componentDidMount () {
     this.setState({ loading: true });

     try {      
       await this._fetchData();
     }
     catch (error) {
       this.props.onError(error); // Or something rendered in state.error?
     }
     finally {
       this.setState({ loading: false });
     }
  }

  render () {
    const { images, posts, loading } = this.state;

    if (!images.length) {
      return <div>No data.</div>;
    }

    if (loading) {
      return <div>Loading</div>;
    }

    const postBoxes = posts.map((post, index) => {
      const image = images[index];
      // Because you don't know, if that specific image is there... if this are your data..
      const imageElement = image ? 
         <img src={image.src} alt="dont know" /> :
         null;
      const { name, price } = post;

      // If name is unique, otherwise some id.
      return (
        <Fragment key={name} >
          {imageElement}

          <h2>{name}</h2>
          <h3>{price}</h3>            
        </Fragment>
      );      
    });

    return (
      <div>
        <Head>
          <title>Онлайн магазин KIKI.BG</title>
          <link rel="icon" href="/favicon.ico" />
        </Head>

        <Fragment>
          {postBoxes}
        </Fragment>
      </div>
    );
  }

  async _fetchData () {
    const { data } = await api.get('products', { per_page: 20 });

    const { posts, images } = data;

    this.setState({ posts, images });
  }
}


export default App;

【讨论】:

    【解决方案3】:

    如果console.log(images.src) -> 给出图像列表。

    那么,

    &lt;img src={images.src[0]}/&gt; -> 应该可以解决问题。

    可能,加个空检查确定。

      images.src[0] && <img src={images.src[0]}/>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-13
      • 1970-01-01
      • 2020-06-15
      • 2016-03-23
      • 2019-08-29
      • 2019-08-04
      • 1970-01-01
      • 2016-06-28
      相关资源
      最近更新 更多