React - 状态属性未定义 - 为什么?

问题描述 投票:0回答:1

当用户单击

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,
    });
}

类型错误:this.state.companies 未定义

这是发生错误的部分:

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

如何解决这个问题?

javascript reactjs
1个回答
2
投票

使用此结构:

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

每次组件收到

任何 props
时,你都会更新 state.companies,即使 props 中没有
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,
      });
    }
}

顺便说一句,我在评论中提到的成功回调范围的问题可能仍然适用。

© www.soinside.com 2019 - 2024. All rights reserved.