简体   繁体   English

与 Js/React 数组相关的问题

[英]Issue related to Js/React arrays

I'm creating an array of indexes in which I'm appending values(this will later be used in a map function).我正在创建一个indexes数组,在其中附加值(稍后将在 map 函数中使用)。

let indexes = [];
export default function SortTiles() {

    let num = info.num_tiles;
    for (let i = 10; i < num+10; i++) {
        indexes = [...indexes, i];
    }
    console.log(indexes);
    console.log("UWU")

    return(
        <div id={"sort-tiles"}>
            {/*{indexes.map(makeTiles)}*/}
        </div>
    )
}

But when I'm trying to console.log my array this is the output I'm getting: The output image The output is being printed twice and the numbers in the array are also duplicated.但是当我试图 console.log 我的数组时,这是我得到的输出:输出图像输出被打印两次,数组中的数字也被复制。

Not sure what are you trying to achieve but this is not the proper way to handle arrays or any data in react component.不确定您要达到什么目的,但这不是处理数组或反应组件中的任何数据的正确方法。

Try this may be this will help you or might fix your problem.试试这个可能会帮助你或可能解决你的问题。

import {useState, useEffect} from 'react';

export default function SortTiles() {

  const [indexes, setIndexes] = useState([]);

  useEffect(() => {
    let num = 20;
    let indexArr = []
    for (let i = 10; i < num+10; i++) {
      indexArr = [...indexArr, i];
    }
    setIndexes(indexArr);
  }, [])


return(
    <div id={"sort-tiles"}>
        {indexes.map((ind) => (<div>{ind}</div>))}
    </div>
)
}

The array is printed twice most likely because you are in strict mode , which double renders components to help catch bugs.该数组最有可能被打印两次,因为您处于严格模式,它会双重渲染组件以帮助捕获错误。

Lucky for you, it helped you catch one!你很幸运,它帮助你抓住了一个! The values are duplicated because the indexes variable is declared outside the function.这些值是重复的,因为indexes变量是在函数外部声明的。 Since you never reset it to an empty value, every re-render will just continue adding indexes.由于您从未将其重置为空值,因此每次重新渲染都会继续添加索引。 Try initializing it inside the function.尝试在函数内部对其进行初始化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM