useState向组件添加状态变量,让组件“记住”用户输入等信息。
https://react.dev/reference/react/useState
定义一个数字变量
import React from 'react';
import { useState } from 'react';
export function StateFunc() {
const [age, setAge] = useState(28);
function handleClick() {
setAge(age + 1);
setAge(age => age +1);
}
return <span onClick={handleClick}>you pressed me {age} times</span>;
}
注意:纯函数定义的名字 StateFunc首字母需要大写, setAge需要定义在function里面。
age是定义的变量, setAge是更新的函数,参数传更新的值,或者age=> {} 更新的函数。
定义一个object变量。
const [form, setForm] = useState({ firstName: 'Taylor'});
function handleClick() {
setForm({...form, firstName: 'Tom'})
}
注意:直接更改object对象,在进行setState,变量值不会改变。
obj.x = 10; // 🚩 Wrong: mutating existing object
setObj(obj); // 🚩 Doesn't do anything
定义嵌套的object
const [nestForm, setNestForm] = useState({ firstName: 'Taylor', person: {age: 24}});
setNestForm({...nestForm, person: {...nestForm.person, age: 26}})
定义数组
const initialTodos = [
{ id: 0, title: 'Buy milk', done: true },
{ id: 1, title: 'Eat tacos', done: false },
{ id: 2, title: 'Brew tea', done: false },
];
const [array, setArray] = useState(initialTodos);
setArray([...array, {id: 3, title:'test AA', done: true}]);
注意:如果使用function定义初始值, 应使用useState传入方法名,避免多次渲染,只渲染一次,但会直接调用函数并存储结果。
function createInitialArray() {
const initialTodos = [
{ id: 0, title: 'Buy milk', done: true },
{ id: 1, title: 'Eat tacos', done: false },
{ id: 2, title: 'Brew tea', done: false },
];
return initialTodos;
}
const [array, setArray] = useState(createInitialArray);
注意:使用() =>来传递函数,这样 React 会存储你传递的函数。
const [fn, setFn] = useState(() => someFunction);
function handleClick() {
setFn(() => someOtherFunction);
}
使用key重置组件
export function StateFunc() {
const [version, setVersion] = useState(1);
function handleClick() {
setVersion(3);
}
return <div>
<span onClick={handleClick}>
</span>
<Form key={version}></Form>
</div>
}
function Form () {
const [name, setName] = useState("Simth");
return <div>
<input value={name} onChange={e => setName(e.target.value)} />
<span> hi, form {name}</span>
</div>
}
当key值发生改变时,会重置form组件
报错: “Too many re-renders”
// 🚩 Wrong: calls the handler during render
return <button onClick={handleClick()}>Click me</button>
// ✅ Correct: passes down the event handler
return <button onClick={handleClick}>Click me</button>
// ✅ Correct: passes down an inline function
return <button onClick={(e) => handleClick(e)}>Click me</button>
注意:只有组件、初始化器和更新器函数需要是纯的。
好了,那我们的useState到这里就结束了。
宝子们可以收藏评论交流哦
网友评论