javascript - setState 函数未定义

标签 javascript reactjs jsx

我是 ReactJS 的新手,正在尝试修改由 API 调用的响应填充的表单的值。我希望能够修改每一行中收到的委托(delegate)人并在另一个字段中获取它们的总和。 onChange 处理函数是:

handleAmortScheduleChange(field , key ,e  ){
            const value = e.target.value;

            this.setState({
            [get_schedule[key][field]] : value,
            [get_emi_amount]:get_schedule[key]["principal"] + get_schedule[key]["interest"],
            [get_schedule[key]["closing_balance"]] : get_schedule[key]["starting_balance"] - get_emi_amount

           });                         
            var arr = document.getElementsByName('get_schedule_principal_here');
            var tot=0;
            for(var i=0;i<arr.length;i++){

                if(parseInt(arr[i].value))
                    tot += parseInt(arr[i].value);
            }
            document.getElementById('get_total_principal').value = tot;

        }

JSX 代码是:

{this.state.get_schedule.map((row,key) =>

<div key={key} className="row aaaa">

    <div className="getAmort-form-group col-xs-12 col-sm-12 col-md-2 col-lg-2">
        <input ref = "get_schedule_emi_date" type="date" required="required" id="get_schedule_emi_date"  value={row.date} />
        <label for="input" className="getAmort-control-label">EMI Date</label><i className="getAmort-bar"></i>
    </div>
    <div className="getAmort-form-group col-xs-12 col-sm-12 col-md-2 col-lg-2">
        <input ref = "get_schedule_emi_amount" type="number" required="required" id="get_schedule_emi_amount"  value={row.amount}/>
        <label for="input" className="getAmort-control-label">EMI Amount</label><i className="getAmort-bar"></i>
    </div>
    <div className="getAmort-form-group col-xs-12 col-sm-12 col-md-2 col-lg-2">
        <input ref = "get_schedule_principal" type="number" required="required" id="get_schedule_principal" name="get_schedule_principal_here" value={row.principal} onChange={this.handleAmortScheduleChange.bind(this, "principal",key)}/>
        <label for="input" className="getAmort-control-label">Principal</label><i className="getAmort-bar"></i>
    </div>
    <div className="getAmort-form-group col-xs-12 col-sm-12 col-md-2 col-lg-2">
        <input ref = "get_schedule_interest" type="number" required="required" id="get_schedule_interest"   value={row.interest} onChange={this.handleAmortScheduleChange.bind(this, "principal",key)} />
        <label for="input" className="getAmort-control-label">Interest</label><i className="getAmort-bar"></i>
    </div>
    <div className="getAmort-form-group col-xs-12 col-sm-12 col-md-2 col-lg-2">
        <input ref = "get_schedule_starting_balance" type="number" required="required" id="get_schedule_starting_balance"  value={row.starting_balance }/>
        <label for="input" className="getAmort-control-label">Starting Balance</label><i className="getAmort-bar"></i>
    </div>
    <div className="getAmort-form-group col-xs-12 col-sm-12 col-md-2 col-lg-2">
        <input ref = "get_schedule_closing_balance" type="number" required="required" id="get_schedule_closing_balance"  value={row.closing_balance}/>
        <label for="input" className="getAmort-control-label">Closing Balance</label><i className="getAmort-bar"></i>
    </div>

</div>)}
<div className="row">
    <div className="getAmort-form-group col-xs-12 col-sm-12 col-md-2 col-lg-2">
        <input  type="number" required="required" id="get_total_principal" />
        <label for="input" className="getAmort-control-label">Total Principal</label><i className="getAmort-bar"></i>
    </div>

    <div className="getAmort-form-group col-xs-12 col-sm-12 col-md-2 col-lg-2">
        <input  type="number" required="required" id="get_total_interest" />
        <label for="input" className="getAmort-control-label">Total Interest</label><i className="getAmort-bar"></i>
    </div>
</div>

get_schedule 是 API 响应中的一个数组,其中包含表单中所有字段的值。我本质上是试图更改用户输入的本金和利息的值,并在 get_schedule 数组中设置它们各自的值。

我在 handleAmortScheduleChange 函数中遇到的错误是 Uncaught ReferenceError :get_schedule 未定义。我也无法设置利息或本金的状态。我哪里出错了,解决方案是什么?

编辑1:根据要求,在组件类中定义get_schedule和其他一些参数。

class LoanDetails extends Component {

    constructor(props) {
        this.state={
            get_schedule            : [],
            get_interest            : 0,
            get_principal           : 0,
            get_starting_balance    : 0,
            get_closing_balance     : 0,
            get_emi_date            : 0,
            get_emi_amount          : 0,
     }
}

API 响应中设置为 get_schedule 的值是:

get_schedule: [{discount: 0, amount: 501, starting_balance: 1000, interest: 1, date: "2019-01-06",…},…]
0: {discount: 0, amount: 501, starting_balance: 1000, interest: 1, date: "2019-01-06",…}
amount: 501
closing_balance: 500
date: "2019-01-06"
discount: 0
interest: 1
principal: 500
starting_balance: 1000
1: {discount: 0, amount: 501, starting_balance: 500, interest: 1, date: "2019-02-06", closing_balance: 0,…}
amount: 501
closing_balance: 0
date: "2019-02-06"
discount: 0
interest: 1
principal: 500
starting_balance: 500

最佳答案

如果错误是 setState 未定义,您将丢失 this 上下文。您可以为您的 handleAmortScheduleChange 函数尝试箭头函数吗?

    handleAmortScheduleChange = (field , key ,e  ) => {
        const value = e.target.value;

        this.setState({
        [get_schedule[key][field]] : value,
        [get_emi_amount]:get_schedule[key]["principal"] + get_schedule[key]["interest"],
        [get_schedule[key]["closing_balance"]] : get_schedule[key]["starting_balance"] - get_emi_amount

       });                         
        var arr = document.getElementsByName('get_schedule_principal_here');
        console.log(arr.length);
        console.log(arr);
        var tot=0;
        for(var i=0;i<arr.length;i++){

            if(parseInt(arr[i].value))
                tot += parseInt(arr[i].value);
                console.log(tot);
        }
        document.getElementById('get_total_principal').value = tot;

    }

如果错误是get_schedule未定义,可能是因为您执行异步操作,并且当它到达渲染函数时它是未定义的,我强烈建议检查您的代码流程。如果您添加更多代码,我可以为您提供更多线索,但同时尝试以下语法。

// double check if get_schedule is ready to use
{this.state.get_schedule && this.state.get_schedule.map((row,key) =>

    {
       /*  now map the row and key to inputs */
    }

}

要解决 get_schedule 中的 get_schedule 错误,您可以将函数更改为箭头函数并使用 this.get_schedule

handleAmortScheduleChange = (field , key ,e  ) => {
    const value = e.target.value;

    this.setState({
    [this.get_schedule[key][field]] : value,
    [get_emi_amount]:this.get_schedule[key]["principal"] + this.get_schedule[key]["interest"],
    [this.get_schedule[key]["closing_balance"]] : this.get_schedule[key]["starting_balance"] - get_emi_amount

   });                         
    var arr = document.getElementsByName('get_schedule_principal_here');
    console.log(arr.length);
    console.log(arr);
    var tot=0;
    for(var i=0;i<arr.length;i++){

        if(parseInt(arr[i].value))
            tot += parseInt(arr[i].value);
            console.log(tot);
    }
    document.getElementById('get_total_principal').value = tot;

}

我修复了您的代码的沙盒版本,您可以在此处找到它。

我修复的内容如下:

  1. 对于 React 中的标签,请使用 htmlFor 而不是普通的 for
  2. 您的某些输入没有 onChangeHandler 我只是留下了一些 onchange 处理程序来解决错误,但请确保以您喜欢的方式填充以下输入的处理程序。 (输入的 EMI_Date、EMI_Amount、CLOSING 和 START Balance onchange)...
  3. 主要错误我使用了不同的设置状态方法。

通常,如果您想要对状态进行的更新取决于当前状态,我们使用以下语法,因为它更安全:)

 this.setState(prevState => ({
      value: prevState.value + 1
    })); 

https://codesandbox.io/s/o4k6nmr4l5

请告诉我你的想法?没有错误,但我对这种形式的计算一无所知:)

关于javascript - setState 函数未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53822463/

相关文章:

javascript - 为什么useReducer要这样设置呢?是不是感觉代码写反了?

reactjs - 导入 4 个文件夹深的文件

javascript - ReactJS 教程 (tic tac) 创建 HTML block 意外标记错误

javascript - AngularJS:无法访问 Controller 中的对象属性

javascript - 我无法使用 GeoSearch 在 Leaflet map 中正确搜索位置

reactjs - 如何在React中正确更新<select multiple ...>?

css - 在下拉组件中添加图像和 div

javascript - 使用 for 循环将值添加到数组

javascript - 在 redux 中在哪里调度多个 Action ?

javascript - React 有没有从 js 到 jsx 的编译器?