ReactJS 中 useEffect Hook 中递增索引计数器的问题

Issue with incrementing index Counter inside useEffect Hook in ReactJS

在这部分代码中,我尝试使用状态变量 'lastIndex' 并尝试使用 setlastIndex 增加它,但 lastIndex 的值不会增加并保持为 0 。我是 React Hooks 的新手,请帮助我。如果之前在堆栈溢出中已经询问过这样的确切查询,那么请发送 link.

function App() {
  const [myAppointment, setmyAppointment] = useState([])
  **const [lastIndex, setlastIndex] = useState(0)** 
  const [orderBy, setorderBy] = useState('petName')
  const [orderDir, setorderDir] = useState('asc')
  const [queryText, setqueryText] = useState('')
  useEffect(() => {
      fetch('./data.json')
      .then(response=> response.json())
      .then(result=>{
        **const apts=result.map(item=>{
          item.aptId = lastIndex
          setlastIndex(lastIndex => lastIndex+1)
          return item
        })**
        setmyAppointment(apts)
      })
  },[])

你应该明白,lastIndex不会在你每次调用setlastIndex函数时增加,所以只要在循环外声明它并在每次分配给aptId 属性时增加。并在循环设置状态后使用最后一个值

then(result=>{
  let currentIndex = lastIndex
  result.forEach(item=>{
    item.aptId = ++currentIndex
  })
  setmyAppointment(result)
  setlastIndex(currentIndex)
})

map不需要,可以用result保存在setmyAppointments