【问题标题】:React: getting TypeError when trying to return JSON response from fetch API callReact:尝试从 fetch API 调用返回 JSON 响应时出现 TypeError
【发布时间】:2021-03-05 10:42:02
【问题描述】:

我有 Node 服务器和 REST API,它以 JSON 格式返回联系信息,现在我试图在用户单击某个菜单按钮时向用户显示该信息。我的服务器工作正常,但在尝试显示数据时出现错误消息:

TypeError: Cannot read property 'state' of undefined

这是我的 React 代码:

import './App.css';
import MenuItems from './components/Navbar/MenuItems';
import ReactDOM from 'react-dom'
import React, { useState } from 'react'

function App() {

  const [selectedItem, setSelectedItem, contacts] = useState();
  getContactInfo();
  return (
    <div className="App">
      <div className="content">
        <h1>My website</h1>
        {MenuItems.MenuItems.map((item, index) => (
          <li key={index} onClick={() => setSelectedItem(item.title)}
          style={{cursor: "pointer"}}>{item.title}</li>
        ))}
        {selectedItem && (
          <h1 style={{textAlign: 'center'}}>{selectedItem}</h1>
        )}
        {selectedItem == 'Contact_us' &&
        <div>
          {this.state.contacts.map(contacts => 
          <div key={contacts.name}> {contacts.phone} </div>)}
        </div>
        }

      </div>
    </div>
    
  );
}
function getContactInfo() {
    fetch('http://127.0.0.1:5000/listUsers')
    .then(res => res.json())
    .then(contacts => this.setState({contacts}))
    .catch(console.log)
}

export default App;

基本上,我试图在用户单击菜单按钮之前从服务器获取信息,并在单击菜单按钮后显示它。我这样做是为了避免“未定义”异常,但它似乎没有帮助。任何建议都非常感谢。

【问题讨论】:

标签: javascript node.js reactjs fetch-api


【解决方案1】:

UseState 的语法如下:

const [state, setState] = useState(initialState);

(https://reactjs.org/docs/hooks-state.html)

您的联系人需要单独的状态:

const [contacts, setContacts] = useState({})

然后在 getContactInfo() 函数中使用 setContact 来设置联系人状态:

function getContactInfo() {
    fetch('http://127.0.0.1:5000/listUsers')
    .then(res => res.json())
    .then(contacts => setContacts(contacts))
    .catch(console.log)
}

另外,getContactInfo() 函数需要在您的应用程序中,目前超出范围。

【讨论】:

    猜你喜欢
    • 2017-09-13
    • 1970-01-01
    • 2021-11-22
    • 2021-12-28
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多