xiaochengzi6 / Blog

个人博客
GNU Lesser General Public License v2.1
0 stars 0 forks source link

react 中操作数组出现的问题 #55

Open xiaochengzi6 opened 2 years ago

xiaochengzi6 commented 2 years ago

IDE在线版

import { useEffect, useState } from 'react';

export default function App() {
  const [instruct, setInstruct] = useState([0, 1, 2]);

  const increase = () => {
    console.log('lastArr', instruct);
    const length = instruct.length - 1;
    const _instruct = instruct.slice();
    const target = ++_instruct[length];
    console.log('现在的问题:', target);
    _instruct.push(target);
    setInstruct(_instruct);
    console.log('currentArr', _instruct);
  };

  return (
    <div>
      <button onClick={increase}>Click</button>
    </div>
  );
}

image 这里的 ++[0,1,2][2] 看样子会修改原数组的中2 索引的值然后在赋值给 target

xiaochengzi6 commented 2 years ago

倒不是是react 中的问题 数组中原本就不能这样使用 image