我正在尝试使用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;