diff --git a/src/App.js b/src/App.js index 5d2ab59..7bbb44d 100644 --- a/src/App.js +++ b/src/App.js @@ -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
Hello world By Class
+ return
+
Hello world By Class
+
state => {this.state.a}
+ +
+ + +
+ + +
{this.state.arr}
+
+ +
+
} }