从 child 组件调用时回调函数不起作用

Call Back function doesn't work when call from child component

我想更改 child 组件的 parent 状态。 我认为我的代码正确但不起作用。

const [newValidate, setNewValidate] = useState<Array<boolean>>(new Array(checkList.length).fill(false));

这是我的parent状态

 {checkList.map((row, index) => {
        const changeValidate = () => {
          setNewValidate(newValidate.splice(index, 1, true));
        } return ( <>
                    <ConfirmButton callBack={changeValidate} />
                    <RejectButton callBack={changeValidate} />
                  </>)})}

这是我在 parent 组件

中的地图
export function ConfirmButton(props: ButtonProps) {
const { callBack } = props;
return (
<>
  <IconButton
    onClick={() => callBack()}
    className={classes.confirm}
    aria-label="confirm check"
  >
    <CheckIcon />
  </IconButton>
</>
);
}

这是我的 child 组件

问题

array.prototype.splice 改变数组。

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

const changeValidate = () => {
  setNewValidate(newValidate.splice(index, 1, true)); // <-- mutation
}

解决方案

如果您尝试更新特定索引处的值,您需要浅复制整个状态数组。将前一个状态映射到下一个状态,当映射索引 i 与封闭的 index return 匹配时更新值,否则 return 现有值。我建议还使用功能状态更新,因为下一个状态数组 depends 依赖于前一个状态数组。

const changeValidate = () => {
  setNewValidate(
    newValidate => newValidate.map((el, i) => i === index ? true : el
  );
}