TypeError: undefined is not a function with React 和 Express

Posted

技术标签:

【中文标题】TypeError: undefined is not a function with React 和 Express【英文标题】:TypeError: undefined is not a function with React and Express 【发布时间】:2020-03-07 04:07:48 【问题描述】:

我正在尝试使用 react 和 express 将此数组的内容输出到我的网页:

["LocationName":"LIBERTY DOGS","Address":"105 Greenwood Ave N, Seattle WA","Available":"Y","LocationName":"FREEDOM DOGS","Address" :"105 Greenwood Ave N, Seattle WA","Available":"Y"]

我不断收到“未处理的拒绝 (TypeError): undefined is not a function (near '...this.state.vendors.map...')”

这是我在 React 中与我的后端通信并将其显示在我的网页上的脚本:

import React from "react";
import  Component  from "react";
// import VendorRenderBox from './VendorRenderBox';
import AdminSideNav from "../components/AdminSideNav";
import  Container, Row, Col  from "react-bootstrap";

class AdminPage extends Component 
  constructor() 
    super();
    this.state = 
      vendors: []
    ;
  
  componentDidMount() 
    fetch("http://localhost:3000/admin/vendors/")
      .then(res => res.json)
      .then(vendors => this.setState( vendors ));
  
  render() 
    return (
      <Container fluid>
        <Row>
          <Col xs="4" sm="3" md="3" lg="2" xl="2" style= paddingLeft: "0" >
            <AdminSideNav />
          </Col>
          <Col
            xs="8"
            sm="9"
            md="9"
            lg="10"
            xl="10"
            style= paddingTop: "75px" 
          >
            <h6> Active list of vendors: </h6>
            <ul>
              this.state.vendors.map(vendor => (
                <li key=vendor.LocationName> vendor.Address </li>
              ))
            </ul>
            /* <AdminRenderBox /> */
          </Col>
        </Row>
      </Container>
    );
  


export default AdminPage;

【问题讨论】:

基本上是在告诉你vendors 不是一个数组,因为它没有map 方法。您是否尝试过记录 vendors 以检查其内容? 是的,同意@BetoFrega 你应该登录。不确定您在前端使用的是什么fetch,但猜测它的响应没有json,所以res.json 是未定义的。可能是res.datares.body 【参考方案1】:

执行 json() 方法:

  .then(res => res.json())

而不是

  .then(res => res.json)

【讨论】:

非常感谢 Richard Nelson,这就是它所花费的一切。谢谢!非常感谢!

以上是关于TypeError: undefined is not a function with React 和 Express的主要内容,如果未能解决你的问题,请参考以下文章

TypeError: undefined is not an object (评估'_order.default.addOrder')

为啥当我点击更新按钮时出现错误TypeError: r is undefined?

TypeError: undefined is not a function (in '...styled Components.default.button...')

TypeError: undefined is not a function with React 和 Express

JQUERY DataTable -- TypeError: k is undefined - 使用 MVC 动态形成表

TypeError: undefined is not an object , item is from an array from an API