反应错误:未处理的拒绝(TypeError):this.state.categories.map不是函数

时间:2020-08-22 08:48:10

标签: javascript reactjs frontend

**我正在尝试从一些课程/视频中学习反应,我几次都收到此错误,并找出并解决了,但现在我不知道了。有人可以帮我吗?而且我尝试不使用“ this”,但是没有用 这是错误: **

   Unhandled Rejection (TypeError): this.state.categories.map is not a function
    CategoryList.render
    C:/Users/Casper/Desktop/Programlar/React-Dersleri/intro/src/CategoryList.js:31
      28 | <div>
      29 |     <h3>{this.props.info.title}</h3>
      30 |     
    > 31 |     <ListGroup>
         | ^  32 |         {
      33 |             this.state.categories.map(category => (
      34 |                 <ListGroupItem active={category.categoryName===this.props.currentCategory?true:false}
    View compiled
    ▶ 18 stack frames were collapsed.
    (anonymous function)
    C:/Users/Casper/Desktop/Programlar/React-Dersleri/intro/src/CategoryList.js:21
      18 |    }
      19 | 
      20 |    getCategories = ()=>{
    > 21 |        fetch("http://localhost:3000/categories")
         | ^  22 |        .then(response=>response.json())
      23 |        .then(data=>this.setState({categories:data}));;
      24 |    }

这是我的代码:

import React, { Component } from 'react'
import Navi from './Navi' //bulunduğum klasörden naviiyi import et
import CartSummary from './CartSummary'

import ProductList from './ProductList'
import {ListGroup,ListGroupItem} from 'reactstrap'



export default class CategoryList extends Component {
   
    state = {
        categories: []
    };

    componentDidMount(){
        this.getCategories();
    }

    getCategories = ()=>{
        fetch("http://localhost:3000/categories")
        .then(response=>response.json())
        .then(data=>this.setState({categories:data}));;
    }
    
    render() {
        return (
            <div>
                <h3>{this.props.info.title}</h3>
                
                <ListGroup>
                    {
                        this.state.categories.map(category => (
                            <ListGroupItem active={category.categoryName===this.props.currentCategory?true:false}
                            onClick={()=>this.props.changeCategory(category)} 
                            key={category.id}>
                                {category.categoryName}
                            </ListGroupItem>
                        ))

                    }
                    
                </ListGroup>
                { <h4>{this.props.currentCategory}</h4> }
            </div>
        )
    }
}

1 个答案:

答案 0 :(得分:1)

由于我们可以看到您使用categories正确初始化了[],因此我们知道初始状态不是问题。因此,我们看一下状态更新。

您要更新的唯一地方categories在这里:

getCategories = ()=>{
    fetch("http://localhost:3000/categories")
    .then(response=>response.json())
    .then(data=>this.setState({categories:data}));;
}

所以这意味着第二个data回调中的.then不是数组(因为如果是数组,它将有一个map方法)。

两个可能的原因:

  1. 您的端点返回的任何JSON都不只是一个类别数组。您需要查看devtools的“网络”选项卡,或在该.then回调中添加一个断点,以便了解其实际返回的内容-可能是一个具有提供类别数组的属性的对象。

  2. 您根本看不到端点响应,但是仍然看到可以解析为JSON的内容。之所以会发生这种情况,是因为除非您从中进行此操作的页面位于http://localhost:3000上,否则您将进行跨域的Ajax调用,除非响应中包含必要的信息,否则Same Origin Policy会阻止该调用Cross-Origin Resource Sharing标头以允许它。 (您的服务器可能还需要处理OPTIONS HTTP调用。)

关于#2,您可能会错过以下事实:您没有获得成功的响应,因为您的代码已成为fetch API步枪的牺牲品:您需要在调用{{1}之前检查HTTP是否成功},因为json仅拒绝针对 network 错误而不是 HTTP 错误的承诺。关于on my anemic little blog的更多信息,但基本上您需要将其更改为:

fetch

getCategories = ()=>{ fetch("http://localhost:3000/categories") .then(response => { // *** if (!response.ok) { // *** throw new Error("HTTP error " + response.status); // *** } // *** return response.json(); // *** }) // *** .then(data => this.setState({categories:data})) .catch(error => { // *** // Handle/report error. // *** }); // *** } 的检查是检查HTTP是否成功。另请注意,我添加了拒绝处理程序。您始终需要处理拒绝,或将promise链返回到可以解决的问题上。 (在这种情况下,您需要处理它; response.ok不会。)

但是,再次重申,这本身并不能解决问题。我想说这很可能是#1的原因,如果SOP错误恰好是您可以解析为JSON的话,那会有点奇怪。