我正在使用 React Sortable HOC 来移动项目。我的初始状态是一个空数组,我需要使用 React Sortable 中的函数来更新状态。
这是 React Sortable HOC 的原始片段
onSortEnd = ({oldIndex, newIndex}) => {
this.setState(({items}) => ({
items: arrayMove(items, oldIndex, newIndex),
}));
};
我的状态和功能如下所示
const [colors, setColors] = useState([])
function onSortEnd({ oldIndex, newIndex }) {
setColors([...colors, ({ colors }) => ({
colors: arrayMove(colors, oldIndex, newIndex)
})]);
};
最终发生的事情是没有错误,但是当我尝试排列任何现有颜色时,会添加更多颜色。
最佳答案
根据提到的要求,我认为您不需要 setState
的回调格式,您可以简单地执行
const [colors, setColors] = useState([])
function onSortEnd({ oldIndex, newIndex }) {
const newColors = arrayMove(colors, oldIndex, newIndex);
setColors(newColors);
};
关于javascript - 如何在 useState 中使用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764192/