我能用钩子解决这个问题吗?
为什么它不能正常工作?
我开始使用REACT DND,在我尝试使用拖放后,所有的事情都出了问题。
我将其用作依赖项:
>
“@testing-library/jest-dom”:“^4.2.4”,
"@testing-library/react":"^9.5.0",
已部署项目-hunger-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);
出现此错误是因为您正在循环内部使用钩子。钩子实现禁止这样做,您可以在这里找到更多内容:
在此输入链接说明
因此,您可能需要在单独的组件中分离todo项,以便在组件顶部使用钩子。