反应挂钩无法正确更新数组

时间:2020-03-07 00:44:42

标签: javascript reactjs react-hooks

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

例如,

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

呼叫删除功能

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

但是,它没有使用新值正确地更新数组,只是将“#”字符的位置与其左侧的字符交换了位置。我怀疑这是因为当我调用删除函数时,我连续两次调用了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>
  );
}

1 个答案:

答案 0 :(得分:0)

不需要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>
  );
}