【问题标题】:turning a validate function from if statements to a switch statements将验证函数从 if 语句转换为 switch 语句
【发布时间】:2018-03-09 19:05:09
【问题描述】:

我有一个我正在重构的 react 表单。我要将大部分状态和逻辑移至父级,因为父级状态将使用表单结果进行更新......但我之前打算重构并且似乎无法让 switch 语句工作。有人告诉我,从长远来看,这将有助于提高性能。

Validate 函数是我尝试添加 switch 语句的地方。

 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

我将 switch 语句放在了 validate 函数中。我尝试了输入、错误、this.state.input、this.state.errors、{input}……我错过了什么?

【问题讨论】:

  • 为什么要使用switch语句?我看不出哪里有必要。
  • 您无法通过单个开关重现相同的功能。谁告诉你它会帮助提高性能显然没有事先查看代码。这是代码试图完成的最简单、最有效的方法。
  • RAD,我会记下来的。我以为是一个非常聪明的家伙告诉我的,但他可能没有看过代码,谢谢!

标签: javascript reactjs ecmascript-6 refactoring


【解决方案1】:

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

if(x === 1){
//...
} else if(x === 2) {
//...
} else if(x === 3) {
//...
} else {} {
//...
}``` 

=>

switch (x) { 
  case 1: 
  //... 
  break;
  case 2: 
  //... 
  break;
  case 3: 
  //... 
  break;
  default: 
  //...
}

因为它清楚地表达了这种“一个变量到多个值”的映射条件。

在您的情况下,尽管您没有将一个 var 与多个值进行比较,但您只需检查多个变量是否存在,即在语义上将它们与真实值进行比较,因此 switch 没有多大意义。

最好保持原样,因为所有这些 if 都在检查不同的条件并且仍然非常可读。

总体而言,您可以查看this article 以获取有关更有效地处理条件的更详细说明。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    相关资源
    最近更新 更多