未处理的拒绝(TypeError):this.state.products.map不是函数

时间:2019-03-19 16:45:05

标签: reactjs

import React, { Component } from 'react';
import axios from 'axios';
import './StoreFront.css';

class StoreFront extends Component {
  constructor() {
    super();

    this.state = {
        products: []
    }
}

componentDidMount() {
    axios.get("url")
        .then((response) => {
            this.setState({
                products: response
            })
        })
}

render() {
    let productDisplay = this.state.products.map((element, index) => {
        return (
            <div className="product-container" key={index}>
                <h2>{element.title}</h2>
                <img src={element.image} alt="" />
                <h2>{element.desc}</h2>
                <h3>{"$" + element.price + ".00"}</h3>
                <button onClick={() => this.props.addToShoppingCart(element)}>Purchase!</button>
            </div>
        )
    })
    return (
        <div className="storefront-container">
            {productDisplay}
        </div>
    )
}
}

 export default StoreFront;

我已经看了一遍,当控制台登录时,我在products数组中得到了一堆对象。我在chrome中使用了调试器,并且该错误始终始于链接24或“让productDisplay = this.state.products.map” 我可以在以下产品中放置一个对象:[{}],但完成后这些值是不确定的。 google中的大多数响应都在处理.json包或将项目设置为字符串,并像它们仍然是数组一样起作用。

2 个答案:

答案 0 :(得分:1)

问题在于this.state.products不是数组。

唯一可能发生这种情况的地方是代码的这一部分。

componentDidMount() {
    axios.get("url")
        .then((response) => {
            this.setState({
                products: response
            })
        })
}

response可能是对象而不是数组。

我不确定您要做什么,但是也许您可以在数组中添加响应。

let newProducts = [...this.state.products]
newProducts.push(response)
this.setState({
    products: newProducts 
})

要以正确的方式解决此问题,请向您的问题中添加response调用中axios的内容。

编辑:,如antoinechalifour在评论中所述:

  

由于他们使用的是Axios,我想应该是产品:response.data,其中数据是实际产品数组。

这也是可能的解决方案。

答案 1 :(得分:0)

问题在于产品的状态不是数组。 您可以在再次设置状态之前检查产品数组是否存在。

this.setState({
    products: {...this.state.products ? this.state.products : '', response}
})
相关问题