1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| import React from 'react'
class StateDemo extends React.Component { constructor(props) { super(props)
this.state = { count: 0 } } render() { return <div> <p>{this.state.count}</p> <button onClick={this.increase}>累加</button> </div> } increase = () => { this.setState({ count: this.state.count + 1 })
this.setState({ count: this.state.count + 1 }, () => { console.log('count by callback', this.state.count) }) console.log('count', this.state.count)
setTimeout(() => { this.setState({ count: this.state.count + 1 }) console.log('count in setTimeout', this.state.count) }, 0)
this.setState({ count: this.state.count + 1 }) this.setState({ count: this.state.count + 1 }) this.setState({ count: this.state.count + 1 }) this.setState((prevState, props) => { return { count: prevState.count + 1 } }) this.setState((prevState, props) => { return { count: prevState.count + 1 } }) this.setState((prevState, props) => { return { count: prevState.count + 1 } }) } bodyClickHandler = () => { this.setState({ count: this.state.count + 1 }) console.log('count in body event', this.state.count) } componentDidMount() { document.body.addEventListener('click', this.bodyClickHandler) } componentWillUnmount() { document.body.removeEventListener('click', this.bodyClickHandler) } }
export default StateDemo
const list5Copy = this.state.list5.slice() list5Copy.splice(2, 0, 'a') this.setState({ list1: this.state.list1.concat(100), list2: [...this.state.list2, 100], list3: this.state.list3.slice(0, 3), list4: this.state.list4.filter(item => item > 100), list5: list5Copy })
this.setState({ obj1: Object.assign({}, this.state.obj1, {a: 100}), obj2: {...this.state.obj2, a: 100} })
|