如何重写冗余的方法声明并创建一个更短的方法声明?

How to rewrite redundant method declaration and create a shorter one?

我声明了相同的 const 值(某种程度上)。这是我目前所拥有的...

import React from 'react'

function Component_a() {
   const x = 5;
   const y = 10;
   const image_a = [...Array(x)].map((e, i) =>
       <div className="image" key={i}>
           <img src="img/image.png" alt="" />
       </div>
   )
   const image_b = [...Array(y)].map((e, i) =>
       <div className="image" key={i}>
           <img src="img/image.png" alt="" />
       </div>
   )
   return (
      {/*some more codes*/}
   )
}

export default Component_a

看起来有点烦人,尤其是当我像这样添加更多冗余行时。感谢您的帮助。

因为唯一需要改变的是数组的长度,只需从中创建一个函数,然后调用该函数两次(或根据需要多次调用):

const makeImages = length => Array.from(
  { length },
  (_, i) => (
    <div className="image" key={i}>
      <img src="img/image.png" alt="" />
    </div>
  )
);

function Component_a() {
   const x = 5;
   const y = 10;
   const image_a = makeImages(x);
   const image_b = makeImages(y);
   return (
      {/*some more codes*/}
   )
}

一个是做这样的事情,将两个数组组合成一个数组并循环遍历它们

const [image_a,image_b] = [[...Array(x)],[...Array(y)]].map((v, i) =>
        v.map((e,i)=>
       <div className="image" key={i}>
           <img src="img/image.png" alt="" />
       </div>
     )
 )

另一种方法:如果有很多这样的数组,您应该使用函数方法

let getHtml = (arr) => arr.map((e,i)) =>
                     <div className="image" key={i}>
                        <img src="img/image.png" alt="" />
                     </div>

然后把数组传给它

   let image_a = getHtml(array1)