繁体   English   中英

使用 State 评估 React 中的 if 语句

[英]Evaulating if-statements in React using State

我一直在正确评估 if 语句时遇到问题,在传递变量或使用要评估的状态变量时总是显示为真或表现出奇怪的行为。 我知道这可能是不同对象的问题或 setState 的异步性质,但我不确定/如何/它是有效的。

希望得到帮助,了解如何正确评估,如果需要任何额外的代码,我会添加,但这应该涵盖我的整体表单验证示例所需的所有内容。

状态

constructor(props)
    {
        super(props);

        this.state = 
        {
            newProfile: 
            {
                name: '',
                email: '',
                gender: '',
                userType: '',
                password: ''        
            },

            match: true,
            formValid: false,
            nameValid: false,
            emailValid: false,
            genderSelectionValid: false,
            userTypeValid: false,
            passwordValid: false,

            formErrors: 
            {
                name: '',
                email: '',
                password: '',
                gender: '',
                userType: ''
            },

            passwordConfirm: '',

            profileOptions: ['Investor', 'Student'],
            genderOptions: ['Male','Female','Other'],

            first: true
        };
        this.handleGenderChange = this.handleGenderChange.bind(this);
        this.handleNameChange = this.handleNameChange.bind(this);
        this.handleEmailChange = this.handleEmailChange.bind(this);
        this.handlePasswordChange = this.handlePasswordChange.bind(this);
        this.handleSecondPasswordChange = this.handleSecondPasswordChange.bind(this);
        this.handleUserTypeChange = this.handleUserTypeChange.bind(this);
        this.handleFormSubmission = this.handleFormSubmission.bind(this);
        this.validateName = this.validateName.bind(this);
        this.validateForm = this.validateForm.bind(this);
    }

表格选择

            <Select options = {this.state.genderOptions}
                    placeholder = {'Select Gender'}
                    handleChange = {this.handleGenderChange}
                    title = {'Gender'}
            />

表单选择jsx

import React from 'react';

const Select = (props) =>
{
    return(
        <div className='form-group'>
            <label> {props.title} </label>
            <select
                value={props.value}
                onChange={props.handleChange}>
                required
                <option>{props.placeholder}</option>
                {props.options.map(field => 
                { return(
                    <option
                        key={field}
                        value={field}
                        label={field}>{field}
                    </option>
                    );
                    })}
            </select>
        </div>)
}

export default Select;

此示例的按钮处理程序

    handleGenderChange(event)
    {
        console.log(event.target.value);
        let value = event.target.value;
        let tempProfile = this.state.newProfile;
        tempProfile.gender = value;
        this.setState({newProfile: tempProfile});
        console.log(this.state.newProfile.gender);
        this.validateGenderSelection(value);
    }

验证性别选择

validateGenderSelection(gender)
    {
        let localFormErrors = this.state.formErrors;

        if(gender == "Male" || "Female" || "Other")
        {
            localFormErrors.gender = "";
            this.setState({genderSelectionValid: true});
        }
        else
        {
            localFormErrors.gender = "No gender selected.";
            this.setState({genderSelectionValid: false});
        }
        this.setState({formErrors: localFormErrors});
        this.validateForm();
    }

整体表单验证

    validateForm()
    {
        if(this.state.nameValid === true && this.state.emailValid === true && this.state.passwordValid === true && this.state.userTypeValid === true && this.state.genderSelectionValid === true)
        {
        this.setState({formValid: true});
        }
        if(this.state.formValid === false)
        {
            console.log(this.state.formErrors);
        }
        console.log(this.state.newProfile.gender);
        console.log(this.state.nameValid, this.state.emailValid, this.state.genderSelectionValid, this.state.userTypeValid, this.state.passwordValid, this.state.formValid);
    }

this.setState是异步的,并且在像这样的常规函数​​上进行批处理......

使用它来检查组件更新了多少次

    componentDidUpdate() {
      console.log('update', this.state);
    }

为了使您的工作

validateGenderSelection(gender)
    {
        let localFormErrors = {...this.state.formErrors};

        if(gender == "Male" ||gender == "Female" || gender =="Other")
        {
            localFormErrors.gender = true;
            this.setState({genderSelectionValid: true});
        }
        else
        {
            localFormErrors.gender = "No gender selected.";
            this.setState({genderSelectionValid: false});
        }
        this.setState({formErrors: localFormErrors}, this.validateForm);
    }
    validateForm()
    {
        if(this.state.nameValid === true && this.state.emailValid === true && this.state.passwordValid === true && this.state.userTypeValid === true && this.state.genderSelectionValid === true)
        {
        this.setState({formValid: true});
        }
        if(this.state.formValid === false)
        {
            console.log('this.state.formErrors', this.state.formErrors);
        }
        console.log(this.state.newProfile.gender);
        console.log(this.state.nameValid, this.state.emailValid, this.state.genderSelectionValid, this.state.userTypeValid, this.state.passwordValid, this.state.formValid);
    }

此外,为什么要为每个值维护太多状态......我认为你可以使状态更好更干净

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM