React Hooks未正确更新数组



我有一个变量数组和一个索引变量,用"#"符号表示。我正在尝试实现一个delete方法,它将删除数组中"#"字符左侧的字符。

例如,

myArray = ["A", "B", "C", "#"]
index = 3

调用删除功能

myArray = ["A", "B", "#"]
index = 2

然而,它并没有用新值正确地更新数组,只是简单地将"#"字符的位置与其左侧的字符交换。我怀疑这是因为当我调用delete函数时,我连续两次调用useState钩子。这是原因吗?如果是,我该如何解决?这是我的密码。

https://codesandbox.io/s/silly-tree-378p4

import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [variables, updateVariables] = useState(["A", "B", "C", "#"]);
const [index, updateIndex] = useState(3);
const decrementIndex = (c = 1) => updateIndex(i => i - c);
const swap = (array, i, j) => {
let temp = array[i];
array[i] = array[j];
array[j] = temp;
return array;
};
const moveCursorLeft = () => {
if (!(index === 0)) {
swap(variables, index, index - 1);
updateVariables(variables);
decrementIndex();
}
};
const deleteCharacter = () => {
const head = variables.slice(0, index - 1);
const tail = variables.slice(index, variables.length);
updateVariables(oldVariables => {
let newVariables = [...oldVariables];
newVariables = head.concat(tail);
return newVariables;
});
moveCursorLeft();
};
return (
<div>
<button
style={{ width: "50px", height: "50px" }}
onClick={() => deleteCharacter()}
/>
<span>
{variables.map(v => (
<var> {v} </var>
))}
</span>
</div>
);
}

应该不需要moveCursorLeft函数。通过在deleteCharacter中进行切片,您已经将其向左移动了。

import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [variables, updateVariables] = useState(["A", "B", "C", "#"]);
const [index, updateIndex] = useState(3);
const decrementIndex = (c = 1) => updateIndex(i => i - c);
const deleteCharacter = () => {
updateVariables(oldVariables => [
...oldVariables.slice(0, index - 1),
...oldVariables.slice(index)
]);
decrementIndex();
};
return (
<div>
<button
style={{ width: "50px", height: "50px" }}
onClick={() => deleteCharacter()}
/>
<span>
{variables.map(v => (
<var> {v} </var>
))}
</span>
</div>
);
}

相关内容

  • 没有找到相关文章

最新更新