为了账号安全,请及时绑定邮箱和手机立即绑定

在空的输入字段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 关注
  • 236 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信