React Native 替换数组中的一个元素是替换数组中的每个元素吗?

hc8w905p  于 6个月前  发布在  React
关注(0)|答案(2)|浏览(87)

我有一个数组,我想搜索,只需要在搜索中放置一个匹配的项目,就像这样:
数组和代码示例:

const test = [
  { id: 0, title: 'test1', seen: false },
  { id: 1, title: 'test2', seen: false },
  { id: 2, title: 'test3', seen: true },
];

字符串
我需要能够搜索测试数组的ID:2,并将其设置为'看到:真'
我试过了:

const [testarray, testTestArray] = usestate(test);
const checkID = 2;

const updateStatus = (checkID) => {

    const new_data = testarray.data.map(id => {
    if (id === checkID) {
      // No change
      return id;
    } else {
      return {
        ...id,
        seen: true,
      };
    }
  });

  setTest(new_data);


我已经用不同的方式玩过了,最接近的是把它们都改成了“看到:真实”?
我不明白什么?
谢谢

ej83mcc0

ej83mcc01#

您正在检查idcheckIDcheckID永远不会相等,因为您正在比较object(数组中的每个单独对象)与number
您必须将其与id.id进行比较,或者为了更好的命名约定,将obj.idcheckID进行比较。
CODESANDBOX

const updateStatus = (checkID) => {
    console.log(checkID);
    const new_data = testarray.map((obj) => {
      if (obj.id === checkID) {
        return {
          ...obj,
          seen: true
        };
      } else {
        return obj;
      }
    });

    setTestArray(new_data);
  };

字符串
你可以把它更简单地描述为:

const updateStatus = (checkID) => {
    const new_data = testarray.map((obj) => ({
      ...obj,
      seen: obj.id === checkID ? true : obj.seen
    }));

    setTestArray(new_data);
  };

m528fe3b

m528fe3b2#

让我们解决这个问题:

const [array, setArray] = useState(test);
const checkID = 2;

const updateStatus = (checkID) => {
  const new_data =  array.map(item => {
    // here was the major mistake
    if (item.id === checkID) {
      return {
        ...item,
        seen: true,
      };
    } else {
      // No change
      return item;
    }
  });
  setArray(new_data);
}

字符串
错误是:

  • 用不同的名字。
  • 不使用item属性,而是使用item本身进行比较。
  • if-else块相对于所询问的内容被反转。

我希望一切都被理解。

相关问题