React setState更新

时间:2018-03-02 22:26:44

标签: javascript reactjs

所以我试图从API列出项目。我真的不知道我的代码有什么问题。我不断收到错误。

事情是state.product使用api数据正确更新。

这是我得到的错误:

  

this.state.product.map不是函数

有人可以在这里帮助我吗

import React, { Component } from 'react';
import { getTranslate, getActiveLanguage } from 'react-localize-redux';
import { connect } from 'react-redux';

// Api Services
import Product from '../../api/product';

class ListProducts extends Component {
    constructor() {
        super();
        this.state = {
            deleteProductModalIsOpen: false,
            products: []
        };
    }

    componentDidMount() {
        let __this = this;

        Product.getAll(function(res) {

            __this.setState({ products: res });
        });
     }

    render() {
        const products = this.state.products.map((item) => ([
            <div className="photo-container" style={{ backgroundImage: 'url("/img/samples/photo.png")' }}></div>,
            item.reference_provider,
            item.label,
            <BarCode img="/img/samples/bar-code.png" code={item.code}/>,
            <Input type="select-table" placeholder={this.props.translate('generic.type')} options={[
                { value: '1', label: <div><div className="dot danger"/> &nbsp; Rupture</div> },
                { value: '2', label: <div><div className="dot warning"/> &nbsp; À commander</div> },
                { value: '3', label: <div><div className="dot info"/>&nbsp; Pris en compte</div> },
                { value: '4', label: <div><div className="dot success"/> &nbsp; En stock</div> }
            ]}/>,
            item.rellacotionproducts.length,
            <div className="action-buttons">
                <a href="/list-products-activity#AdjustStocksModal">
                    <div className="tooltip">
                        <Button type={"table-action"} action={"less-gray"}/>
                        <div className="tooltip-text">{this.props.translate('Button.less')}</div>
                    </div>
                </a>
                <a href="/list-products-activity#AdjustStocksModal">
                    <div className="tooltip">
                        <Button type={"table-action"} action={"plus-gray"}/>
                        <div className="tooltip-text">{this.props.translate('Button.plus')}</div>
                    </div>
                </a>
                <a href={"/edit-product/" + item.id }>
                    <div className="tooltip">
                        <Button type={"table-action"} action={"edit"}/>
                        <div className="tooltip-text">{this.props.translate('Button.edit')}</div>
                    </div>
                </a>
                <div className="tooltip">
                    <Button onClicked={this.openDeleteProductModal.bind(this)} type={"table-action"} action={"delete"}/>
                    <div className="tooltip-text">{this.props.translate('Button.delete')}</div>
                </div>
            </div>
        ]));


        return (
            <div className="list-products">
                <Page/>
                <div className="page-container">
                    <div className="page-header">
                        <h1><img src="/img/list-products-header-icon.png"/> &nbsp;{this.props.translate('ListProducts.title')}</h1>
                        <div className="action-buttons">
                            <Input type="search" label={this.props.translate('generic.search')}/>
                            <Button type={"action"} action="export" label={this.props.translate('Button.export')}/>
                            <Button type={"action"} action="create" label={this.props.translate('Button.fast_create')}/>
                            <Button type={"action"} action="print" label={this.props.translate('Button.print')}/>
                        </div>
                    </div>
                    <div className="page-main">
                        <Table
                            pagination={true}
                            rowsPerPage="8"
                            head={[
                                <div>{this.props.translate('generic.photo')} &nbsp; </div>,
                                <Input type="search-th" label={this.props.translate('ListProducts.reference')}/>,
                                <Input type="search-th" label={this.props.translate('generic.tag')}/>,
                                <Input type="search-th" label={this.props.translate('ListProducts.barcode')}/>,
                                <div>{this.props.translate('generic.type')} &nbsp;<img src="/img/table-header-order-arrow.png"/></div>,
                                <div>{this.props.translate('ListProducts.quantity_stock')} &nbsp;<img src="/img/table-header-order-arrow.png"/> &nbsp; &nbsp; </div>,
                                this.props.translate('ListProducts.action')
                            ]}
                            body={
                                products
                            }/>
                    </div>
                </div>
            </div>
        );
    }
}

const mapStateToProps = state => ({
    translate: getTranslate(state.locale),
    currentLanguage: getActiveLanguage(state.locale).code
});

export default connect(mapStateToProps)(ListProducts);

这也是API服务器的响应:

"products": [
    {
        "id": 53,
        "productoreqpt": true,
        "reference_company": null,
        "label": null,
        "type": null,
        "description": null,
        "code": null,
        "code_gentype": null,
        "category": [],
        "tags": [],
        "size": null,
        "color": null,
        "reference_provider": null,
        "statut": null,
        "dimlenght": null,
        "dimwidth": null,
        "dimtall": null,
        "weight": null,
        "unit": null,
        "perishable_duration": null,
        "dangerous": null,
        "maker": null,
        "gps": null,
        "supplier": null,
        "variation": null,
        "variation_mother": null,
        "variation_carac": null,
        "internal_code": null,
        "archive": null,
        "created": "2018-03-02T16:18:20+0000",
        "modified": "2018-03-02T16:18:20+0000",
        "company_id": 0,
        "env_id": 0,
        "user_num_1": null,
        "user_num_2": null,
        "user_num_3": null,
        "user_num_4": null,
        "user_num_5": null,
        "user_date_1": null,
        "user_date_2": null,
        "user_date_3": null,
        "user_date_4": null,
        "user_date_5": null,
        "user_text_1": null,
        "user_text_2": null,
        "user_text_3": null,
        "user_text_4": null,
        "user_text_5": null,
        "user_boo_1": null,
        "user_boo_2": null,
        "user_boo_3": null,
        "user_boo_4": null,
        "user_boo_5": null
    }

好的,那么更新。产品似乎是一个数组,但它立即转为undefined,这是一个控制台日志enter image description here

3 个答案:

答案 0 :(得分:1)

res是否为数组。 map仅适用于数组。使用console.log(res)检查它是否为数组。如果没有将其转换为数组

答案 1 :(得分:1)

问题出在__this.setState({ products: res });基本上,您是因为res不是数组类型而导致此错误,因此您必须检查它并确保它是一个数组类型,因为其他已经提到了。

如果您仍然遇到同样的错误,我建议您安装console.log res并将其添加到您的问题中。

答案 2 :(得分:1)

如果实际上未定义

,请将条件置于res之上
Product.getAll(function(res) {

        __this.setState({ products: (res || __this.state.products) });
    });

希望它有所帮助。