一、state 特点
- react 的state类似于 vue 的 data,是react 的响应式数据
- 直接修改 state 数据是无效的,需要通过对应的方法更改 state 数据后视图才会更新
- state 的修改是一个浅合并的过程,所以修改数组或对象的数据时,需要格外注意
- 当需要修改一个对象的数据,可通过 扩展运算符 setObj({...obj, {name: 'bob'}}) 或者直接复制一份对象的方式进行操作
- 当需要修改数组时,可借助 concat map filter slice 扩展运算符[...arr] 或者直接复制一份数组的方式进行操作
二、state 的使用
1、函数组件中使用 useState 来声明状态变量,使用 setXXX 来更新状态变量
import { useState } from "react";
function Test1 () {
const [a, setA] = useState(1);
const [b, setB] = useState(11);
const [arr, setArr] = useState([1, 2]);
const [obj, setObj] = useState({x: 1, y: 2});
const addA = () => {
setA(a + 1);
};
const addB = () => {
setB(b + 1);
};
const addToArray = () => {
setArr([...arr, arr.length + 1]);
};
const updateObj = () => {
setObj({...obj, x: obj.x + 1, y: 4});
}
return (<div>
<p>Test1</p>
<div>
<p>{a} -- {b} -- {arr.join(",")} -- {JSON.stringify(obj)}</p>
<button type="button" onClick={addA}>a+1</button>
<button type="button" onClick={addB}>b+1</button>
<button type="button" onClick={addToArray}>add to array</button>
<button type="button" onClick={updateObj}>update obj</button>
</div>
</div>);
}
export default Test1;
2、class 组件中使用 this.state 来声明状态变量,使用 this.setState 来更新状态变量
import React from 'react';
class Test2 extends React.Component {
constructor(props) {
super(props);
this.state = {
a: 1,
b: 11,
arr: [1,2],
obj: {x: 1, y: 2}
}
}
addA () {
let _a = this.state.a;
this.setState({
a: _a + 1
})
}
const addB = () => {
const _b = this.state.b
this.setState({
b: _b + 1
})
}
addToArray() {
const _arr = this.state.arr;
_arr.push(_arr.length + 1);
this.setState({
arr: _arr
})
}
updateObj () {
this.setState({
obj: {...this.state.obj, x: this.state.obj.x + 1, y: 4}
})
}
render() {
return(<div>
<p>Test2</p>
<div>
{this.state.a}---{this.state.b}---{this.state.arr.join(",")}---{JSON.stringify(this.state.obj)}
<br></br>
<button type="button" onClick={this.addA.bind(this)}>a+1</button>
<button type="button" onClick={this.addB}>b+1</button>
<button type="button" onClick={this.addToArray.bind(this)}>add to array</button>
<button type="button" onClick={this.updateObj.bind(this)}>update obj</button>
</div>
</div>)
}
}
export default Test2;