【问题标题】:Adding Value in an array by click in a "button"通过单击“按钮”在数组中添加值
【发布时间】:2023-01-11 03:23:08
【问题描述】:

我有一个数组。其值为 Objects。 1个数组中有3个值对于 1 个对象.

这是一个 ReactJS 项目。

比如像这样

const x = useMemo(() => [

[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5, 5],

]);

现在我有一个按钮。

我的问题是“如何或什么功能我可以添加到我的按钮,以便它会改变每个数组的中间值 [1]”

例如:点击按钮后我想在中间值中添加 [ - 0.5 * 2 ].

!!!点击 !!!

const x = useMemo(() => [

[1, 1, 1],
[2, 2, 2],
[3, 3, 3],
[4, 4, 4],
[5, 5 - 0.5 * 2, 5],
[6, 6 - 0.5 * 2, 6]
]);

!!!点击【第二次】!!!

const x = useMemo(() => [

[1, 1, 1],
[2, 2, 2],
[3, 3 - 0.5 * 2, 3],
[4, 4 - 0.5 * 2, 4],
[5, 5 - 0.5 * 2, 5],
[6, 6 - 0.5 * 2, 6]
]);

!!!点击【第三次】!!!

const x = useMemo(() => [

[1, 1 - 0.5 * 2, 1],
[2, 2 - 0.5 * 2, 2],
[3, 3 - 0.5 * 2, 3],
[4, 4 - 0.5 * 2, 4],
[5, 5 - 0.5 * 2, 5],
[6, 6 - 0.5 * 2, 6]
]);

等等。

【问题讨论】:

  • 第四次应该发生什么?前 3 次,所有中间值可能都已转换,所以想知道转换是否不应该发生第 4 次?
  • @SandeepAmarnath 在前 3 次之后,它会转到默认位置。

标签: javascript reactjs arrays three.js react-three-drei


【解决方案1】:

import { useState } from 'react';

export default function DemoPage() {
  const [positions, setPositions] = useState([
    [1, 1, 1],
    [2, 2, 2],
    [3, 3, 3],
    [4, 4, 4],
    [5, 5, 5],
  ]);
  const targetIndex = positions.length - 1;

  const clickHandle = () => {
    const nextPositions = positions.map((items, index) => {
      if (targetIndex === index) {
        // If there are more array items, you can use `.map` .
        // return items.map((value) => value * 2);
        return [items[0], (items[1] - 0.5) * 2, items[2]];
      }
      return items;
    });

    setPositions(nextPositions);
    console.log('positions :>> ', positions);
  };
  return (
    <div>
      <p>position is { positions[targetIndex].join(',') }</p>
      <button type="button" onClick={clickHandle}>Click</button>
    </div>
  );
}

要更新数组,请参见此处:https://beta.reactjs.org/learn/updating-arrays-in-state#replacing-items-in-an-array

推荐使用“use-immer”,这样更容易更新数据。

使用沉浸式:https://www.npmjs.com/package/use-immer

【讨论】:

  • 我可以不使用“useState”吗?
  • 这是实际问题,如您所见,我想更改“位置”的值codesandbox.io/s/5thhhhhhhhhhh-30q7f2?file=/src/components/…
  • 我想问一下你为什么要使用“useMemo”,我对你的需求有点困惑? beta.reactjs.org/reference/react/useMemo
  • 请查看我附上链接的代码。然后你就会明白为什么我要使用“useMemo”。我正在使用“useMemo”来改变房间的位置。但是我不知道还有其他简单的方法可以做到这一点。但是,如果您对“useState”而不是“useMemo”有任何其他解决方案,请告诉我 :) 谢谢!
  • 现在可以正常使用了,问题是因为“useState”在更新数组中的值时没有生效,参见:beta.reactjs.org/learn/…,我用更简单的“useImmer”来更新数据,代码在这里:@ 987654326@
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-02
  • 1970-01-01
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
  • 2021-03-03
  • 2020-06-08
相关资源
最近更新 更多