我正在使用react-sortable-hoc软件包,但想在功能组件中使用它。我尝试将其转换,但是有一行显示给我一个错误。
显示该列表,我可以拖动任何元素,但是一旦将其删除,我就会收到错误
无法读取未定义的属性“切片”
似乎正在发布到此行:
items: arrayMove(items, oldIndex, newIndex),
这是基于类的版本:
import React, {Component} from 'react';
import {render} from 'react-dom';
import {sortableContainer, sortableElement} from 'react-sortable-hoc';
import arrayMove from 'array-move';
const SortableItem = sortableElement(({value}) => <li>{value}</li>);
const SortableContainer = sortableContainer(({children}) => {
return <ul>{children}</ul>;
});
class App extends Component {
state = {
items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
};
onSortEnd = ({oldIndex, newIndex}) => {
this.setState(({items}) => ({
items: arrayMove(items, oldIndex, newIndex),
}));
};
render() {
const {items} = this.state;
return (
<SortableContainer onSortEnd={this.onSortEnd}>
{items.map((value, index) => (
<SortableItem key={`item-${value}`} index={index} value={value} />
))}
</SortableContainer>
);
}
}
render(<App />, document.getElementById('root'));
以及我要放在一起的版本:
import React, { useState } from "react";
import { sortableContainer, sortableElement } from "react-sortable-hoc";
import arrayMove from "array-move";
const SortableItem = sortableElement(({ value }) => <li>{value}</li>);
const SortableContainer = sortableContainer(({ children }) => {
return <ul>{children}</ul>;
});
const Dashboard = () => {
const [items, setItems] = useState([
"Item 1",
"Item 2",
"Item 3",
"Item 4",
"Item 5",
"Item 6",
]);
const onSortEnd = ({ oldIndex, newIndex }) => {
setItems(({ items }) => ({
items: arrayMove(items, oldIndex, newIndex),
}));
};
return (
<SortableContainer onSortEnd={onSortEnd}>
{items.map((value, index) => (
<SortableItem key={`item-${value}`} index={index} value={value} />
))}
</SortableContainer>
);
};
export default Dashboard;
答案 0 :(得分:1)
您不需要destructure items
回调中的setItems
,因为状态不会在您的案例中存储对象,而是存储一个数组。另外,您不得将值重新设置为对象,而应再次将其设置为数组
setItems((items) => arrayMove(items, oldIndex, newIndex));