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
| <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>04_component_state</title> </head> <body>
<div id="example"></div>
<script type="text/javascript" src="./js/react.development.js"></script> <script type="text/javascript" src="./js/react-dom.development.js"></script> <script type="text/javascript" src="./js/babel.min.js"></script>
<script type="text/babel"> class A extends React.Component { state = { m1: {count: 1} }
test1 = () => { /*this.setState(state => ({ m1: {count: state.m1.count + 1} }))*/
// const m1 = this.state.m1 // m1.count = 2 // this.setState({m1}) // this.setState({m1: {...m1}})
this.setState({}) }
render() { console.log('A render()') return ( <div> <h1>A组件: m1={this.state.m1.count}</h1> <button onClick={this.test1}>A 测试1</button> <B m1={this.state.m1}/> </div> ) } }
class B extends React.PureComponent { state = { m2: 1 }
test2 = () => { this.setState({}) }
/* 用来决定当前组件是否应该重新render(), 如果返回true, 就会去重新render(), 否则结束 */ /*shouldComponentUpdate (nextProps, nextState) { console.log('shouldComponentUpdate()') // 比较新旧props中的和state数据, 如果没有一个变化的返回false, 否则true if(this.props.m1===nextProps.m1 && this.state.m2===nextState.m2) { return false } else { return true } // return true // Component中的默认为true }*/
render() { console.log('B render()') return ( <div> <h1>B组件: m2={this.state.m2}, m1.count={this.props.m1.count}</h1> <button onClick={this.test2}>B 测试2</button> </div> ) } }
ReactDOM.render(<A/>, document.getElementById('example')) </script> </body> </html>
|