React State
定义组件状态
React使用 useState
定义组件状态。
例如定一个计数器的状态, useState
函数返回两个值,我们用数组解构的方式将值解构出来。
第一个值是状态本身,第二个是用于修改状态的函数。
const [count, setCount] = useState(0);
更新组件状态
function App() {
const [count, setCount] = useState(0);
function increase() {
setCount((value) => value + 1);
}
function decrease() {
setCount((value) => value - 1);
}
return (
<div className="App">
<h1>Counter</h1>
<p>{count}</p>
<button className="buttonStyle" onClick={increase}>
+
</button>
<button className="buttonStyle" onClick={decrease}>
-
</button>
</div>
);
}
更新数组状态
重点是不要修改原本的 list
数组,而是要将数组复制一遍,然后将复制后的值修改,再赋值回去。
function App() {
const [list, setList] = useState([1, 2, 3, 4]);
function add() {
setList([...list, list.length + 1]);
}
function remove() {
setList(list.slice(0, list.length - 1));
}
return (
<div className="App">
<ul>
{list.map((item) => {
return <li key={item}>{item}</li>;
})}
</ul>
<button className="buttonStyle" onClick={add}>
添加
</button>
<button className="buttonStyle" onClick={remove}>
删除
</button>
</div>
);
}
更新对象状态
function App() {
const [person, setPerson] = useState({
id: 1,
name: "John",
age: 25,
address: "USA",
});
function handleAddGender() {
setPerson((prePerson) => {
return {
...prePerson,
gender: "man",
};
});
}
function handleChangeAge() {
setPerson((prePerson) => {
return {
...prePerson,
age: 26,
};
});
}
function removeChangeAge() {
setPerson((prePerson) => {
// const newPerson = { ...prePerson };
// delete newPerson.age;
// return newPerson;
// or
const { age, ...newPerson } = prePerson;
return newPerson;
});
}
return (
<div className="App">
<ul>
{Object.keys(person).map((key) => {
return (
<li key={key}>
{key}: {person[key]}
</li>
);
})}
</ul>
<button className="buttonStyle" onClick={handleAddGender}>
添加性别
</button>
<button className="buttonStyle" onClick={handleChangeAge}>
修改年龄
</button>
<button className="buttonStyle" onClick={removeChangeAge}>
删除年龄
</button>
</div>
);
}
评论区