React - state属性未定义 - 为什么?

时间:2017-08-03 15:12:18

标签: javascript reactjs

当用户点击state框时,我想通过AJAX请求将所有公司加载到select属性中。

这是代码:

import React, { Component } from 'react';
import SelectOption from './SelectOption';

class CreateFreightEntryModal extends Component {

    constructor(props) {
        super(props);
        this.state = {
            freights: props.freights,
            onClose: props.onClose,
            onClick: props.onClick,
            companies: [],
        };
    }

    loadCompanies(event) {
        $.ajax({
            type: "POST",
            context:this,
            dataType: "json",
            async: true,
            url: "../data/get/json/companies",
            data: ({ 
                _token : window.Laravel.csrfToken,
            }),
            success: function (data) {
                var arr = $.map(data, function(el) { return el; });
                this.setState({
                    companies: arr
                })
            }
        });
    }

    render() {
        return (
            <div className="modal fade" id="createFreightEntryModal" tabIndex="-1" role="dialog">
                <div className="modal-dialog" role="document">
                    <div className="modal-content">
                        <div className="modal-header">
                            <button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 className="modal-title">New freight entry</h4>
                        </div>
                        <div className="modal-body">
                            <div>
                                <div>
                                    <form onSubmit={this.add.bind(this)}>
                                        <div className="row">
                                            <div className="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                                                <strong>Create a new freight entry:</strong>
                                            </div>
                                        </div>
                                        <div className="row">
                                            <div className="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                                                Company
                                            </div>
                                            <div className="col-xs-8 col-sm-8 col-md-8 col-lg-8">
                                                <div className="form-group" onClick={this.loadCompanies.bind(this)}>
                                                    <select className="selectpicker show-tick form-control" data-live-search="true" data-title="Please select" ref="Firma" required>
                                                    {
                                                        this.state.companies.map((company)=> {
                                                          return (
                                                            <SelectOption value={company.Nummer} displayValue={company.Bezeichnung} key={company.id} />
                                                          );
                                                        })
                                                    }
                                                    </select>
                                                </div>
                                            </div>
                                        </div>

                                        <div className="row">
                                            <div className="col-xs-12 col-sm-12 col-md-12 col-lg-12">
                                                <div className="form-group">
                                                    <button type="submit" className="btn btn-success"><span className="glyphicon glyphicon-floppy-disk"></span> Save </button>
                                                </div>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-default" data-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

export default CreateFreightEntryModal

当我添加componentWillReceiveProps(nextProps)方法时,我收到此错误。 加载页面时会出现此错误,而不是在我单击选择框时出现错误!

componentWillReceiveProps(nextProps) {
    this.setState({
        companies: nextProps.companies,
    });
}
  

TypeError:this.state.companies未定义

这是发生错误的部分:

...
this.state.companies.map((company)=> {
...

我该如何解决这个问题?感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

使用此构造:

componentWillReceiveProps(nextProps) {
    this.setState({
        companies: nextProps.companies,
    });
}

每次组件收到 ANY道具时,您都会更新state.companies,即使道具中没有companies也是如此。如果nextProps没有companies,则设置为undefined

让我们这样说明:

{
  let props = { freights : [ 'a', 'b', 'c' ] }
  this.setState({ companies : props.companies }) 
  /* state.companies are now undefined, because props.companies are undefined */
}

修正:

componentWillReceiveProps(nextProps) {
    if( nextProps.companies ){
      this.setState({
          companies: nextProps.companies,
      });
    }
}

BTW我在评论中提到的成功回调范围问题可能仍然适用。