【问题标题】:State is undefined after POST requestPOST 请求后状态未定义
【发布时间】:2021-02-11 12:14:09
【问题描述】:

用于创建 CRUD 电话簿。使用 JSON 服务器作为我的伪装数据库。

当我创建新数据时,它已成功添加到我的数据库中。然而在那一刻我得到状态的错误是未定义的。当我刷新 DOM 时,它显示正常。

我的创建功能如下所示。

  const createContact = async contactObject => {
    await fetch('http://localhost:3001/phonebook', {
      method: 'POST',
      body: JSON.stringify(contactObject),
      headers: {
        'Content-type': 'application/json; charset=UTF-8',
      },
    });
  };

  const contactObject = {
    name: newName,
    number: newNumber,
    date: new Date().toISOString(),
  };

  createContact(contactObject).then(res => setPersons(persons.concat(res)));

初始状态

  const [persons, setPersons] = useState([])

  const getAllContacts = async () => {
    const res = await fetch('http://localhost:3001/phonebook')
    const data = await res.json()
    return data
  }

  useEffect(() => {
    getAllContacts().then(response => setPersons(response))
  }, [])

新数据正在正确添加到我的数据库中onSubmit

{
  "phonebook": [
    {
      "name": "hello",
      "number": "111",
      "date": "2020-10-29T03:02:44.604Z",
      "id": 1
    },
    {
      "name": "world",
      "number": "222",
      "date": "2020-10-29T03:16:00.725Z",
      "id": 2
    }
  ]
}

我已经尝试过让 React 不呈现状态,除非它可用。在我的渲染组件中

export const ContactList = ({ persons }) => {
  return persons.length ? (
    <ul>
      {persons.map(person => (
        <Contact key={person.id} person={person} />
      ))}
    </ul>
  ) : (
    <h1>Loading contacts</h1>
  );
};

我认为在人员可用之前不会尝试列出人员,但它仍然给我persons.id 是未定义的错误。

第一次做 CRUD,所以我不熟悉 React 对此的反应。

【问题讨论】:

  • 您不会从包含 fetch 的方法中返回任何内容。
  • 除了 Dave 写的,在更新状态时使用功能更新,例如setPersons(prev =&gt; prev.concat(res)).

标签: reactjs


【解决方案1】:

需要从函数返回一些东西

 const createContact = async (contactObject) => {
    const res = await fetch('http://localhost:3001/phonebook', {
        method: 'POST',
        body: JSON.stringify(contactObject),
        headers: {
            "Content-type": "application/json; charset=UTF-8"
        }
    })
    const data = await res.json()
    return data

同样在更新状态时,也需要功能更新

.then(data => setPersons(persons => persons.concat(data)))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2021-06-08
    相关资源
    最近更新 更多