【问题标题】:State not updating in react with a nested object (hooks)状态未与嵌套对象(钩子)反应更新
【发布时间】:2021-10-26 12:02:48
【问题描述】:

我一直在玩 react-beautiful-dnd 和 hooks(对 react 来说非常新)——由于某种原因,我的状态不会在拖动时更新。 (编辑:我知道该逻辑仅适用于“相同类别”拖动 - 这对我来说也不更新 UI)

数据(简化)

const skills = {
  skills: {
    skill1: {
      id: "skill1",
      name: "Communication"
    },
    skill2: {
      id: "skill2",
      name: "Empathy"
    },
    skill3: {
      id: "skill3",
      name: "Initiative"
    }
  },
  categories: {
    cat1: {
      id: "cat1",
      name: "Core",
      skillIds: ["skill1", "skill2", "skill3", "skill4"]
    },
    cat2: {
      id: "cat2",
      name: "Craft",
      skillIds: ["skill5", "skill6", "skill7", "skill8"]
    },
    cat3: {
      id: "cat3",
      name: "Leadership",
      skillIds: ["skill9", "skill10"]
    }
  },
  categoryOrder: ["cat1", "cat2", "cat3"]
};

更新skillIds数组到正确类别的函数

const reorder = (list, startIndex, endIndex) => {
    const result = Array.from(list);
    const [removed] = result.splice(startIndex, 1);
    result.splice(endIndex, 0, removed);

    return result;
  };

  const onDragEnd = (result) => {
    const { source, destination } = result;

    // dropped outside the list
    if (!destination) {
      return;
    }

    // Handle moving within one category
    if (source.droppableId === destination.droppableId) {
      const catSkills = data.categories[source.droppableId].skillIds;
      const items = reorder(catSkills, source.index, destination.index);
      const newData = {
        ...data,
        categories: {
          ...data.categories,
          [source.droppableId]: {
            ...data.categories[source.droppableId],
            skillIds: items
          }
        }
      };
      setData(newData);
    }
  };

我创建了一个简化的代码框来测试 - https://codesandbox.io/s/hooks-problem-il5m4

任何帮助表示赞赏!

【问题讨论】:

    标签: reactjs setstate react-beautiful-dnd


    【解决方案1】:

    我可以看到状态正在更新

     if (source.droppableId === destination.droppableId) { setData(data) }
    

    这个“if”子句意味着它只会在拖动发生在同一车道上时更新状态。我认为你试图将它拖动到另一个车道。希望这就是你的意思

    编辑:我了解您的问题。问题是你没有使用更新的数据,你正在循环静态技能。我希望这能解决你的问题

          {data.categoryOrder.map((catId) => {
          const category = data.categories[catId]; //change skills to data
          const catSkills = category.skillIds.map(
            (skillId) => skills.skills[skillId]
          );
    

    【讨论】:

    • 嗯,我想我的意思是拖动动作不起作用,即使在同一车道上拖动(参见codesandbox.io/s/hooks-problem-il5m4)。不确定这是“状态未更新”还是其他未更新 UI?
    • 更新了答案
    • 天哪,谢谢!我盯着错误的代码看了这么久!
    猜你喜欢
    • 1970-01-01
    • 2019-06-13
    • 2021-06-15
    • 2021-08-29
    • 2020-09-24
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多