文章来源:https://mp.weixin.qq.com/s/FSnCz8EhShJMdG_FGf0igQ
1、不用所有的都使用state
import { useRef, useState } from "react";
export default function NoState() {
const [name,setName] = useState("")
const usernameRef = useRef();
const onSubmit = (e) => {
e.preventDefault();
console.log(
"需要提交的数据",
usernameRef.current,
name
);
};
const changeInput = (e)=>{
usernameRef.current = e.target.value
}
const changeStateInput = (e)=>{
setName(e.target.value)
}
console.log("组件重新渲染了");
return (
<form onSubmit={onSubmit}>
<label htmlFor="name">修改ref</label>
<input type="text" onChange={changeInput}/>
<br />
<label htmlFor="name">修改state</label>
<input type="text" onChange={changeStateInput}/>
<br />
<button type="submit">提交</button>
</form>
);
}
当表单元素不多时,使用ref来处理,并且每次输入都不会引起组件的重新渲染,因为这个时候我们只关心提交的数据,没有在其他地方使用过这些state。
如上述处理,每次输入修改state就会重新渲染页面,如果修改的是ref则不会重新渲染页面。