3. 响应式

This commit is contained in:
shikong 2024-10-23 21:24:25 +08:00
parent 591b3eaafa
commit c3c091aad5
Signed by: Shikong
GPG Key ID: BD85FF18B373C341

View File

@ -17,13 +17,71 @@ function App() {
// vue2 选项式 API
class ClassHello extends React.Component {
// eslint-disable-next-line no-useless-constructor
// state = {
// a: 0
// }
constructor(props) {
super(props);
this.state = {
a: 0,
arr: [0, 1, 2]
}
}
subValState = () => {
this.setState({
...this.state,
a: this.state.a - 1
})
}
addValState() {
// this.state.a ++
// this.setState({})
this.setState((state) => {
return {
...state,
a: ++state.a,
}
}, () => {
console.log("setState callBack, 能获取到修改后的值 => ", this.state.a)
})
console.log("setState 之外, 获取不到修改后的值 => ", this.state.a)
}
addArr = ()=>{
this.setState((state)=>{
state.arr.push(state.arr[state.arr.length - 1 ] + 1)
return {
...state,
// 解构赋值 使其地址改变 才能触发视图更新
// 不直接操作原对象, 要 先拷贝 再操作
arr: [...state.arr],
}
}, ()=>{
console.log("state.arr => ", this.state.arr)
})
}
render() {
return <div>Hello world By Class</div>
return <div style={{border: '1px solid', width: '80%', overflow: 'auto'}}>
<div>Hello world By Class</div>
<div> state => {this.state.a}</div>
<div style={{display: "flex", justifyContent: "center"}}>
<button onClick={this.subValState}>-1</button>
<button onClick={this.addValState.bind(this)}>+1</button>
</div>
<div>{this.state.arr}</div>
<div style={{display: "flex", justifyContent: "center"}}>
<button onClick={this.addArr}>+1</button>
</div>
</div>
}
}