【问题标题】:React Hooks State with preserving previous state (REACT DND)保留先前状态的 React Hooks 状态 (REACT DND)
【发布时间】:2020-04-16 21:25:48
【问题描述】:

我正在尝试对对象使用 useState 的动态 setState。

const [check, setcheck] = useState({
    q1:'',
    q2:''
})

但我未能保留最后一个状态。每当我开始拖动时,我都会使用 react dnd,它会清除“状态”。我不确定它的渲染或什么或我做错了什么。 我可以选择将状态设置为 localStorage,但请有人检查我的代码块,我将不胜感激。

以下是我的代码

import React, { useState, useEffect } from "react";
import { useDrag } from "react-dnd";
import ItemTypes from "./ItemTypes";
const style = {..}
const ItemBox = ({ url, id, idref }) => {
  const [check, setcheck] = useState({
    q1: "",
    q2: ""
  });

  console.log(check, "CheckState");
  useEffect(() => {
    idref.current = { check };
  }, [check, idref]);
  const [{ isDragging }, drag] = useDrag({
    item: { id, type: ItemTypes.BOX },
    end: (item, monitor) => {
      const dropResult = monitor.getDropResult();
      if (item && dropResult) {

        // * here I am trying to set the state *

        setcheck({ ...check, [item.id]: dropResult.id });
      }
    },
    collect: monitor => ({
      isDragging: monitor.isDragging()
    })
  });

  const opacity = isDragging ? 0.4 : 1;
  return (
    <div
      id={id}
      ref={drag}
      style={{ ...style, opacity, backgroundImage: `url(${url})` }}
    />
  );
};
export default ItemBox;

【问题讨论】:

    标签: reactjs react-hooks react-dnd


    【解决方案1】:

    您应该使用setcheck 的回调版本,因为useDrag 会缓存您传递的选项,因此check 指的是第一次check。

    setcheck((currentCheck) => ({ ...currentCheck, [item.id]: dropResult.id }));
    

    【讨论】:

    • 我已经尝试过这个,遗憾的是不能使用 dragEvent .. 它会清除状态并在我开始拖动项目时从初始状态开始.. 它可能与 reactDND 相关 ??
    • @RebelCoder 当你放下一个项目时,你是否将它移动到另一个容器中(就节点在 DOM 中的渲染位置而言?)
    猜你喜欢
    • 2018-11-24
    • 1970-01-01
    • 2019-11-08
    • 2021-08-07
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    相关资源
    最近更新 更多