React:我们的用法习惯可能是错误的(不优雅)
今天学到了 2023-01-088,361阅读4分钟在我们React的日常开发中一些常用的写法,看似运行的很好,实际可能并不优雅。学习React并不是如何如何使用它,而是如何写出优雅,干净的代码。下面举一些例子,总结了一些React开发中不好的写法及相应更好的写法。(仅代表个人观点)
过多的声明state
问题
一个组件中声明了过多的state,过多的setState方法。例如下面的这样:
ini 复制代码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>
);
}
实际上这样并不好维护,接手项目的人都疯了
标签:function,const,value,用法,React,useState,import,return,优雅 From: https://www.cnblogs.com/sexintercourse/p/17728068.html