javascript - 在空输入字段 ReactJS 上显示错误

标签 javascript reactjs

我正在尝试根据两个文本输入字段中是否都有任何字符来启用/禁用表单按钮,但由于某种原因,尽管我记录了状态,但由于某种原因,状态长度在我的条件下呈现错误它出现了。

错误:

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

        event.preventDefault();
        var route = `${API_ROOT}` + '/api/annotation/' + this.props.annotationId + '/share/email';
        fetch(route,
            {
                method: 'POST', 
                body: JSON.stringify(body),
                compress: false,
                headers: { 
                    'X-CSRF-Token': this.props.csrf,
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
            .then(res => {
                return res.json();
            })  
            .then(data => {
                this.handleClearForm();
                this.props.shareFlashMessage('success');
                this.setState({'flash': 'success'});
                this.props.closeShareModal(false);
            }) 
            .catch(err => {
                console.log(err);
                this.props.shareFlashMessage('error');
                this.setState({'flash': 'error'});
            });
    }


    render() {
        var emailSubject;  
        {
            this.state.subject 
                ? 
            emailSubject = this.state.subject 
                : 
            emailSubject = this.props.title
        };

        console.log(this.state) // csrf: '', subject: undefined, emails: '', comment: ''
        console.log(this.state.subject) // renders undefined

        const isEnabled = this.state.subject.length > 0 && this.state.emails.length > 0; //Uncaught TypeError: Cannot read property 'length' of undefined

        return (
            <div className="annotation-footer__share-form-email">
                <form action={"/api/annotation/" + this.props.annotationId + "/share/email"} method="post" onSubmit={this.handleFormSubmit} name="annotationEmailShare" id="share-email-form">
                    <div className="input-group annotation-footer__share-form-email-inputs">
                        <p><b>Subject:</b></p>
                        <input type="text" name="subject" className="form-control" defaultValue={this.props.title} onChange={this.handleInputChange}/><br />
                    </div>
                    <div className="input-group annotation-footer__share-form-email-inputs">
                        <p><b>Emails (Comma separate each email address):</b></p>
                        <input type="text" name="emails" className="form-control" onChange={this.handleInputChange}/><br />
                    </div>
                    <div className="input-group annotation-footer__share-form-email-inputs">
                        <p><b>Additional Comment (Optional):</b></p>
                        <textarea name="comment" rows="4" className="form-control" onChange={this.handleInputChange}></textarea><br />
                    </div>
                    <button type="submit" disabled={!isEnabled}>Send Email</button>
                </form>
            </div>
        )
    }
}

最佳答案

似乎 this.props.title 未定义。

要解决此问题,请检查 this.props.title 值,并仅在具有有效值时更新状态。像这样:

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

建议:

不是在 didMount 方法中使用 props 值更新 subject,而是在构造函数本身中执行它,就像这样:

this.state = {
  csrf: '',
  subject: props.title || '',
  emails: '',
  comment: ''
}

关于javascript - 在空输入字段 ReactJS 上显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55667287/

相关文章:

javascript - 如何在 *.js.erb 文件上运行 eslint?

javascript - React 通过 onclick 调用组件

javascript - 如何在 ReactJs 中正确使用 componentWillUnmount()

reactjs - 从 AWS Amplify 上托管的 React 应用程序的 protected 路由访问拒绝错误

Reactjs useContent Hook 在使用上下文时返回未定义

javascript - 我需要获取 like_count from_like 信息

javascript - CSV 文件未重新加载(Google GeoCharts)

javascript - jQuery.animate 滚动问题

javascript - Jasmine 中使用外部库进行单元测试

javascript - React JS - 如何优化渲染代码?