【问题标题】:Uncaught RangeError: Maximum call stack size exceeded in React application未捕获的 RangeError:React 应用程序中超出了最大调用堆栈大小
【发布时间】:2023-01-22 19:28:57
【问题描述】:

请帮我。 我是 React 的新手,尝试构建一个应用程序以在本地存储中添加联系人和删除联系人。以下是我的 App.js 的代码

import React, {useState, useEffect} from 'react'
import {uuid} from 'uuidv4'
import AddContact from './AddContact'
import ContactList from './ContactList'
import Header from './Header'

function App() {
  //useState Hooks in React
  const LOCAL_STORAGE_KEY = 'contacts'
  const [contacts, setContacts] = useState([])

  const addContactHandler = (contact) => {
    console.log(contacts)
    setContacts([...contacts, {id: uuid(), ...contact}])
  }

  const removeContactHandler = (id) => {
    const newContactList = contacts.filter((contact) => {
      return contact.id !== id
    })
    setContacts(newContactList)
  }
  useEffect(() => {
    const retrieve_contact = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY))
    if (retrieve_contact) {
      setContacts(retrieve_contact)
    }
  }, [])

  useEffect(() => {
    localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(contacts))
  }, [contacts])

  return (
    <div className="ui container">
      <Header />
      <AddContact addContactHandler={addContactHandler} />
      <ContactList contacts={contacts} getContactId={removeContactHandler} />
    </div>
  )
}

export default App

我收到错误 Uncaught RangeError: Maximum call stack size exceeded。

请帮助我如何消除此错误。 谢谢!

【问题讨论】:

  • 请登录retrieve_contact。我愿意打赌 retrieve_contact 永远是真实的价值
  • @captain-yossarian 即使那是真的,也没有理由导致无限循环。 useEffect 挂钩只会执行一次。
  • @BenWainwright 你是对的
  • 我在这一行中遇到的问题`setContacts([...contacts, { id: uuid(), ...contact }]);` id:uuid() 当我删除 id: uuid() 然后我得到了每个元素的相同键
  • 它到底是什么时候说的?单击某物后或立即?看起来更多的代码和解释将有助于更容易地理解问题

标签: javascript html css reactjs typescript


【解决方案1】:

您正在 useEffect 中更新状态,这会触发无限循环。如果将 setContacts 调用移到 useEffect 挂钩之外,它应该会停止错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-04
    • 2020-10-02
    • 2012-06-17
    • 2018-02-28
    • 2017-04-12
    • 2014-08-01
    相关资源
    最近更新 更多