React错误的习惯用法分析详解
糖瓶 人气:0过多的声明state
在我们React的日常开发中一些常用的写法,看似运行的很好,实际可能并不优雅。学习React并不是如何如何使用它,而是如何写出优雅,干净的代码。下面举一些例子,总结了一些React开发中不好的写法及相应更好的写法。(仅代表个人观点)
问题
一个组件中声明了过多的state,过多的setState方法。例如下面的这样:
import { useState } from "react"; export default function MoreState() { const [username, setUsername] = useState(""); const [age, setAge] = useState(""); const [gender, setGender] = useState(""); const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [address, setAddress] = useState(""); const [city, setCity] = useState(""); const onSubmit = () => { // ... }; return ( <form onSubmit={onSubmit}> <input type="text" name="username" placeholder="username" value={username} onChange={(e) => setUsername(e.target.value)} /> <br /> <input type="text" name="age" placeholder="age" value={age} onChange={(e) => setAge(e.target.value)} /> <br /> <input type="text" name="gender" placeholder="gender" value={gender} onChange={(e) => setGender(e.target.value)} /> <br /> <input type="text" name="email" placeholder="email" value={email} onChange={(e) => setEmail(e.target.value)} /> <br /> <input type="text" name="password" placeholder="password" value={password} onChange={(e) => setPassword(e.target.value)} /> <br /> <input type="text" name="address" placeholder="address" value={address} onChange={(e) => setAddress(e.target.value)} /> <br /> <input type="text" name="city" placeholder="city" value={city} onChange={(e) => setCity(e.target.value)} /> <br /> <button type="submit">提交</button> </form> ); }
实际上这样并不好维护,接手项目的人都疯了
加载全部内容