React useState 实现,以在重新渲染时保持随机值不变

huangapple go评论70阅读模式
英文:

React useState implementation to keep random value unchanged on re-render

问题

我有一个存储在数组中的名字列表。
每当用户点击添加按钮时,新的名字就会被推送到数组中。
这些名字被渲染在页面上。每个名字在特定div内有随机生成的位置。

每当新的名字被推送到数组中时,数组中所有其他名字的位置都会发生变化。

我相当确定我需要实现 useEffect 钩子,但我无法使其正常工作。

以下是代码:

const randomNum = (min: number, max: number): number => {
  return Math.floor(Math.random() * (max - min + 1) + min);
};

const elements = data.map((el) => {
  return (
    <div
      style={{
        position: 'absolute',
        top: `${randomNum(0, 51)}%`,
        right: `${randomNum(0, 51)}%`,
      }}
    >
      {el.name}
    </div>
  );
});

// 更新名字数组状态的函数
function add(id: number) {
  setData(
    update(data, {
      data: {
        $push: [
          {
            name: '',
            id,
          },
        ] as any,
      },
    })
  );
}

// 触发“add”函数的按钮
<div
  onClick={() => add(data.data.length + 1)}
>
  点击添加
</div>
<div>
  {elements}
</div>

感谢你的帮助。

英文:

I have a list od names stored in array.
Everytime user clicks on the add button, a new name is pushed to the array.
Those names are rendered on the page. Every name has randomly generated position inside a specific div.

Everytime a new name is pushed to the array, a position of all the other names inside an array changes.

I am pretty sure that I need to implement useEffect hook, but I can't get it to work right.

Here is the code

  const randomNum = (min: number, max: number): number =&gt; {
    return Math.floor(Math.random() * (max - min + 1) + min);
  };

  const elements = data.map((el) =&gt; {
    return (
        &lt;div
          style={{
            position: &#39;absolute&#39;,
            top: `${randomNum(0, 51)}%`,
            right: `${randomNum(0, 51)}%`,
          }}
        &gt;
          {el.name}
        &lt;/div&gt;
    );
  });

A function which updates the state of the names array

 function add(id: number) {
    setData(
      update(data, {
        data: {
          $push: [
            {
              name: &#39;&#39;,
              id,
            },
          ] as any,
        },
      })
    );
  }

And a button which triggers the "add" function

       &lt;div
          onClick={() =&gt; add(data.data.length + 1)}
        &gt;
          Click to add
        &lt;/div&gt;
        &lt;div&gt;
           {elements}
        &lt;/div&gt;

Thank you for the help

答案1

得分: 2

function add(id: number) {
setData(
update(data, {
data: {
$push: [
{
name: '',
id,
top: ${randomNum(0, 51)}%,
right: ${randomNum(0, 51)}%,
},
] as any,
},
})
);
}

Also don't forget adding a 'key' (use the 'id') when rendering a list:

const elements = data.map((el) => (


{el.name}

));

英文:

Add to position (top and right) when you add the name, and not when you render it:

function add(id: number) {
    setData(
      update(data, {
        data: {
          $push: [
            {
              name: &#39;&#39;,
              id,
              top: `${randomNum(0, 51)}%`,
              right: `${randomNum(0, 51)}%`,
            },
          ] as any,
        },
      })
    );
  }

Also don't forget adding a key (use the id) when rendering a list:

const elements = data.map((el) =&gt; (
  &lt;div
    key={el.id}
    style={{
      position: &#39;absolute&#39;,
      top: e.top,
      right: e.right,
    }}
  &gt;
    {el.name}
  &lt;/div&gt;
));

huangapple
  • 本文由 发表于 2023年3月9日 21:44:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75685428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定