turning a validate function from if statements to a switch statements

时间:2018-03-09 19:05:09

标签: javascript reactjs ecmascript-6 refactoring

I have a form in react that I'm refactoring. I'm going to move most of the state and logic to the parent, because the parent state will be updated with the form result... but I was going to refactor before and can't seem to get a switch statement to work. I was told it would help performance in the long run.

The Validate function is where I'm trying to add a switch statement.

 import React from 'react'
    import styles from './style.addLibForm.css'

class AddLibForm extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
            input: {
                title: "",
                content: "",
                imgURL: ""
            },
            blurred: {
                title: false,
                content: false,
                imgURL: ""
            },
            formIsDisplayed: this.props.toggle
        };
      }


handleInputChange(newPartialInput) {

  this.setState(state => ({
    ...state,
    input: {
      ...state.input,
      ...newPartialInput
    }
  }))

}

handleBlur(fieldName) {
this.setState(state => ({
    ...state,
    blurred: {
        ...state.blurred,
        [fieldName]: true
      }
  }))
}

***//TURN INTO SWITCH STATEMENT!***
validate() {
    const errors = {};
    const {input} = this.state;

    if (!input.title) {
        errors.title = 'Title is required';
    } //validate email

    if (!input.content) {
        errors.content = 'Content is required';
    }

    if (!input.imgURL) {
        errors.imgURL = 'Image URL is required';
    }
    console.log(Object.keys(errors).length === 0);
    return {
        errors,
        isValid: Object.keys(errors).length === 0
    };
}


render() {
  const {input, blurred} = this.state;
  const {errors, isValid} = this.validate();


  return (

    <div className="flex">
      <form
        className={styles.column}
        onSubmit={(e) =>
          { e.preventDefault();
            this.setState({})
            return console.log(this.state.input);
            }}>

        <h2> Add a library! </h2>


          <label>
            Name:
            <input
              className={styles.right}
              name="title"
              type="text"
              value={input.title}
              onBlur={() => this.handleBlur('title')}
              onChange={e => this.handleInputChange({title: e.target.value})}/>
          </label>
          <br/>



          <label>
            Content:
            <input
              className={styles.right}
              name="content"
              type="text"
              value={input.content}
              onBlur={() => this.handleBlur('content')}
              onChange={e => this.handleInputChange({content: e.target.value})}/>
          </label>
          <br/>


          <label>
            Image URL:
            <input
              className={styles.right}
              name="imgURL"
              type="text"
              value={input.imgURL}
              onBlur={() => this.handleBlur('imgURL')}
              onChange={e => this.handleInputChange({imgURL: e.target.value})}/>
          </label>
          <br/>

        <p>
            <input className={styles.button} type="submit" value="Submit" disabled={!isValid}/>
        </p>

        {/* CSS THESE TO BE INLINE WITH INPUTS */}
        <br/>
        {blurred.content && !!errors.content && <span>{errors.content}</span>}

        <br/>
        {blurred.title && !!errors.title && <span>{errors.title}</span>}
        <br/>
        {blurred.imgURL && !!errors.imgURL && <span>{errors.imgURL}</span>}

      </form>
    </div>
  );
}
  }

export default AddLibForm

I've was putting the switch statement inside the validate function. I tried inputs, errors, this.state.input, this.state.errors, {input}... what am I missing... thanks in advanced...

1 个答案:

答案 0 :(得分:0)

当您需要将一个变量与不同的值进行比较时,切换语句最有意义

{ "key": "cmd+e 1", 
    "command": "editor.action.insertSnippet", 
    "args": { "name": "wrap_mark" } 
},

=&GT;

<mark>

因为它清楚地表达了这个&#34; 1变量到许多值&#34;映射条件。

在你的情况下,虽然你没有比较一个var到多个值,你只需检查多个变量是否存在,即在语义上将它们与truthy值进行比较,因此switch不会有多大意义。

离开时更好,因为所有这些ifs都在检查不同的条件并且仍然非常易读。

总的来说,您可以查看this article以获得更有效处理条件处理的详细说明。

相关问题