【发布时间】: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