React使用知识点汇总
文章来源: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则不会重新渲染页面。
使用 && 常见的错误
1.当状态值不是Boolean,而是数字0时,数字0会在UI中显示。
import { useRef, useState } from "react";
export default function NoState() {
const arr = useRef([])
return (
<div>
{
arr.current.length && <div>11111</div>
}
</div>
);
}
页面显示0;
解决方法
- 转成Boolean
- 使用三元表达式代替 && (推荐)

浙公网安备 33010602011771号