javascript - 如何在 useState 中使用函数

标签 javascript reactjs

我正在使用 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/

相关文章:

JavaScript 或 Rails : How to grab a BLE device or bluetooth

javascript - 当输入聚焦时,React Native 有条件地渲染部分 View

javascript - 如果当前组件发生更改,则停止加载新的路由/组件

javascript - ReactJS:如何在 <div> 内将表单 <Field> 的 &lt;input&gt; 和 <button> 以及 <h1> 对齐?

Javascript 不删除 div 中的所有元素

javascript - new Function(...) 在 Debug模式下在 Chrome 58 中返回 undefined

javascript - jQuery 是否在两个不同的 CSS 类之间进行动画处理?

javascript - 无法获取 setTimeOut 内的 conversationState 属性值

reactjs - 调用 store.writeQuery() 后组件不会重新呈现

css - React Motion CSS 从中心变换