英文:
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 => {
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>
);
});
A function which updates the state of the names array
function add(id: number) {
setData(
update(data, {
data: {
$push: [
{
name: '',
id,
},
] as any,
},
})
);
}
And a button which triggers the "add" function
<div
onClick={() => add(data.data.length + 1)}
>
Click to add
</div>
<div>
{elements}
</div>
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: '',
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) => (
<div
key={el.id}
style={{
position: 'absolute',
top: e.top,
right: e.right,
}}
>
{el.name}
</div>
));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论