亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在空的輸入字段ReactJS上顯示錯誤

在空的輸入字段ReactJS上顯示錯誤

慕妹3146593 2021-04-17 18:15:13
我正在嘗試基于兩個文本輸入字段中是否都存在任何字符來啟用/禁用表單按鈕,但是由于某種原因,狀態長度在我的條件下呈現了錯誤,盡管我登錄狀態時卻顯示了錯誤。錯誤:const isEnabled = this.state.subject.length > 0 && this.state.emails.length > 0; //Uncaught TypeError: Cannot read property 'length' of undefined完整代碼:import React from 'react';export default class EmailAnnotationForm extends React.Component {    constructor(props) {        super(props);        this.state = {            csrf: '',            subject: '',            emails: '',            comment: ''        }        this.handleInputChange = this.handleInputChange.bind(this);        this.handleFormSubmit = this.handleFormSubmit.bind(this);        this.handleClearForm = this.handleClearForm.bind(this);        this.input = React.createRef();    }    componentDidMount() {        console.log(this.state.subject.length) // renders correct value => 0        this.setState({subject: this.props.title });    }    handleInputChange(event) {        const target = event.target;        const value = target.type === 'checkbox' ? target.checked : target.value;        const name = target.name;        this.setState({            [name]: value        });    }    handleClearForm() {        this.setState({            csrf: '',            subject: '',            emails: '',            comment: ''        })    }    handleFormSubmit(event) {        var emailSubject;          {            this.state.subject ? emailSubject = this.state.subject : emailSubject = this.props.title        }; //        const body = {            subject: emailSubject,            emails: this.state.emails,            comment: this.state.comment        };
查看完整描述

1 回答

?
慕桂英546537

TA貢獻1848條經驗 獲得超10個贊

看來this.props.title是不確定的。


要解決此問題,請檢查this.props.title值,并僅在其具有有效值時更新狀態。像這樣:


componentDidMount() {

  if(this.props.title)

    this.setState({ subject: this.props.title });

}

建議:


不用subject在didMount方法中使用props值進行更新,而是在構造函數本身中執行此操作,如下所示:


this.state = {

  csrf: '',

  subject: props.title || '',

  emails: '',

  comment: ''

}


查看完整回答
反對 回復 2021-04-29
  • 1 回答
  • 0 關注
  • 260 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號