闽公网安备 35020302035485号
import { useState } from "react";
// 堆代码 duidaima.com
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>
);
}
实际上这样并不好维护,接手项目的人都疯了。import { useState } from "react";
export default function MoreState() {
const [userInfo, setUserInfo] = useState({
username: "",
age: "",
gender: "",
email: "",
password: "",
address: "",
city: ""
});
const onChange = (e) => {
setUserInfo((pre) => ({ ...pre, [e.target.name]: e.target.value }));
};
const onSubmit = (e) => {
e.preventDefault();
console.log(111, userInfo);
};
return (
<form onSubmit={onSubmit}>
<input
type="text"
name="username"
placeholder="username"
onChange={onChange}
/>
<br />
<input type="text" name="age" placeholder="age" onChange={onChange} />
<br />
<input
type="text"
name="gender"
placeholder="gender"
onChange={onChange}
/>
<br />
<input type="text" name="email" placeholder="email" onChange={onChange} />
<br />
<input
type="text"
name="password"
placeholder="password"
onChange={onChange}
/>
<br />
<input
type="text"
name="address"
placeholder="address"
onChange={onChange}
/>
<br />
<input type="text" name="city" placeholder="city" onChange={onChange} />
<br />
<button type="submit">提交</button>
</form>
);
}
二.不必要的stateimport { useState } from "react";
export default function NoState() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const onSubmit = (e) => {
e.preventDefault();
console.log("需要提交的数据", username, password);
};
console.log("组件重新渲染了");
return (
<form onSubmit={onSubmit}>
<label htmlFor="name">名字</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<br />
<label htmlFor="name">密码</label>
<input
type="text"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<br />
<button type="submit">提交</button>
</form>
);
}
上面的代码看似并没有什么问题,但是我们只是在提交的时候用到了state,并没有在其他地方使用过这些state。这个例子中我们并不关心这些state值的变化,我们只关心我们提交的数据是否正确。而且我们每次输入的时候组件都是重新渲染。这并不友好,这个时候我们需要非受控组件。import { useRef } from "react";
export default function NoState() {
const usernameRef = useRef();
const posswordRef = useRef();
const onSubmit = (e) => {
e.preventDefault();
console.log(
"需要提交的数据",
usernameRef.current.value,
posswordRef.current.value
);
};
console.log("组件重新渲染了");
return (
<form onSubmit={onSubmit}>
<label htmlFor="name">名字</label>
<input type="text" ref={usernameRef} />
<br />
<label htmlFor="name">密码</label>
<input type="text" ref={posswordRef} />
<br />
<button type="submit">提交</button>
</form>
);
}
三.过多的useEffectimport { useEffect, useState } from "react";
export default function MoreUseEffect() {
const [data, setData] = useState();
useEffect(() => {
fetch("/ss/ss").then((res) => {
setData(res.data);
});
}, []);
useEffect(() => {
// 进行其他逻辑处理...
console.log(data);
}, [data]);
return <>页面第一次加载时请求</>;
}
引入了过多的useEfffect,实际上我们只是需要使用请求到的数据来进行其他逻辑的处理,并不需要数据变化时做一些事情。import { useEffect } from "react";
export default function MoreUseEffect() {
useEffect(() => {
fetch("/ss/ss").then((res) => {
// setData(res.data);
// 在这里直接进行数据处理...
console.log('')
});
}, []);
return <>页面第一次加载时请求</>;
}
四.请求竞争问题import { useEffect, useState } from "react";
export default function useFetch(url) {
const [loading, setLoading] = useState(true);
const [data, setData] = useState();
const [error, setError] = useState();
useEffect(() => {
setLoading(true);
fetch(url)
.then((res) => {
setData(res.data);
})
.catch((e) => {
setError(e);
})
.finally(() => setLoading(false));
}, [url]);
return {
loading,
data,
error
};
}
解决方法import { useEffect, useState } from "react";
export default function useFetch(url) {
const [loading, setLoading] = useState(true);
const [data, setData] = useState();
const [error, setError] = useState();
useEffect(() => {
const controller = new AbortController();
setLoading(true);
fetch(url, { signal: controller.signal })
.then((res) => {
setData(res.data);
})
.catch((e) => {
setError(e);
})
.finally(() => setLoading(false));
return () => {
controller.abort();
};
}, [url]);
return {
loading,
data,
error
};
}
import { useState } from "react";
export default function MoreUseEffect() {
const [arr] = useState([])
return <>
{
arr.length && <div>11111</div>
}
</>;
}
解决方法2.使用三元表达式代替 && (推荐)
import {useRef} from 'react'
function InputCom({ref}) {
return (
<input type='text' ref={ref} />
)
}
function App() {
const inpRef = useRef(null)
const focus = () => {
inpRef.current?.focus()
}
return (
<>
<InputCom ref={inpRef} />
</>
)
}
如果想传递ref需要借助forwardRef函数。import { forwardRef, useRef } from "react";
// function InputCom({ ref }) {
// return <input type="text" ref={ref} />;
// }
const InputCom = forwardRef((props, ref) => {
return <input type="text" ref={ref} />;
});
export default function ProRef() {
const inpRef = useRef(null);
const focus = () => {
inpRef.current?.focus();
};
return (
<>
<InputCom ref={inpRef} />
<br />
<button onClick={focus}>focus</button>
</>
);
}