【发布时间】: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