未捕获的类型错误:映射函数不适用于数组变量

时间:2018-07-20 11:48:07

标签: reactjs

我是React的新手。我有一个数组变量,但是当我调用map函数时它不起作用。我收到“未捕获(承诺)TypeError:this.state.products.map不是函数”

class Child extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            products: []
        };

componentDidMount() {
        fetch(url)
            .then((Response) => {
                this.setState({
                    products: Response.json()
                });
            })
            .catch(err => console.error);
    }
}

 render() {
        return (
            <div>
                <div className="col-lg-12">
                    {this.state.products.map(product1 => (
                        <Button key={product1.id} style={{ color: 'grey', radius: '5px', width: '90px' }}>
                            {product1.title}
                        </Button>
                    ))}
                    <br /><br /><br />
                </div>
            </div>
        );
    }
}
export default Category;

我要去哪里错了? 谢谢。

2 个答案:

答案 0 :(得分:2)

Response.json()是一个承诺。 MDN。假设您正在从服务器中获取所需的阵列

componentDidMount() {
        fetch(url)
            .then(res => res.json())
            .then((products) => {
                this.setState({
                    products
                });
            })
            .catch(console.error); // because err => console.error is a noop
    }
}

答案 1 :(得分:0)

我想,当您获得响应时,json响应不是数组:

products: Response.json()

能否请您检查一下它是否实际排列

相关问题