我可以用钩子解决这个问题吗?
为什么它不能正常工作?
我开始使用REACT DND,在尝试对项目进行拖放操作后,一切都出错了。
我用作依赖项:
“ @ testing-library / jest-dom”:“ ^ 4.2.4”,
“ @ testing-library / react”:“ ^ 9.5.0”,
已部署的项目- hungry-tree.surge.sh
src / components / todos / createTodo.js
import React, { useRef } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { useDrag, useDrop } from "react-dnd";
import actions from "../../actions";
const ItemTypes = {
CARD: "todo",
};
function createTodo(props) {
const currTodos = props.todos();
return currTodos.map((elem, index) => {
const ref = useRef(null);
const [{ isDragging }, drag] = useDrag({
item: { type: ItemTypes.CARD, index },
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
});
const [, drop] = useDrop({
accept: ItemTypes.CARD,
hover(item, monitor) {
if (!ref.current) {
return;
}
const dragIndex = item.index;
const hoverIndex = index;
// Don't replace items with themselves
if (dragIndex === hoverIndex) {
return;
}
const dragTodo = props.thirdData[dragIndex];
const todoStart = props.thirdData.slice(0, hoverIndex - 1);
const todoEnd = props.thirdData.slice(hoverIndex);
todoStart.splice(todoStart.indexOf(dragTodo), 1);
todoEnd.splice(todoStart.indexOf(dragTodo), 1);
const withoutTodos = [...todoStart, dragTodo, ...todoEnd];
props.setThirdData(withoutTodos);
item.index = hoverIndex;
},
});
drag(drop(ref));
return (
<li key={index} ref={drag} style={{ opacity: isDragging ? 0.5 : 1 }}>
<span
className={`todos_block-text ${
elem.isComplete ? "todos_block-text_done" : ""
}`}
onClick={() => props.onDoneTodo(elem.label)}
>
{elem.label}
</span>
<button
className="todos_block-trash"
onClick={() => props.onDeleteTodo(elem.label)}
>
x
</button>
</li>
);
});
}
createTodo.propTypes = {
thirdData: PropTypes.array,
setThirdData: PropTypes.func,
};
const mapStateToProps = (store) => {
return {
thirdData: store.thirdData.data,
};
};
const mapDispatchToProps = (dispatch) => {
return {
setThirdData: (data) => dispatch(actions.setThirdData(data)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(createTodo);
答案 0 :(得分:0)
出现此错误是因为您在循环内使用钩子。挂钩实现禁止这样做,您可以在此处找到更多信息:
因此,您可能需要将待办事项分开放在单独的组件中,才能在组件顶部使用钩子。