componentDidMount() 方法会在组件已经render()之后执行,这里可以对dom进行操作,编写加载服务器的数据。
componentWillReceiveProps(nextProps) 初始化render时不会执行,只有当父组件传给当前组件的值发生变化才会执行,可以根据属性变化,调用this.setState()来更新子组件,
这里调用更新状态是安全的,并不会触发额外的render调用,如果在这里进行数据请求,它只会在该组件渲染时才会发出,从而减轻请求负担
class App extends Component { constructor(props) { super(props); this.state = { random:Math.random(), } this.handleClick = this.handleClick.bind(this); } tmpPerson = {name:‘张三‘} handleClick(){ this.tmpPerson.name+=‘1‘; this.setState({random:Math.random()}) } render() { const _this = this; return ( <div classsName="App"> <button onClick={this.handleClick}>修改名称</button> <Demo person={{...this.tmpPerson}}></Demo> {/* {...this.tmpPerson}是对 this.tmpPerson的深拷贝,修改值不会影响原始值,传给组件对象值会变化,则输出值不同*/} {/* <Demo person={this.tmpPerson}></Demo> this.tmpPerson则是引用对象,地址没变,传给子组件的是同一个对象不会变化,则输出值相同*/ } </div> ) } } export default App; class Demo extends Component{ static propTypes={ person:PropTypes.any, } static defaultProps={ person:{name:‘person对象名‘} } constructor(props) { super(props); }; componentWillReceiveProps(nextProps){ console.log(`--this.props-->${JSON.stringify(this.props)}`); console.log(`--nextProps-->${JSON.stringify(nextProps)}`); // --this.props-->{"person":{"name":"张三"}} // --nextProps-->{"person":{"name":"张三1"}} } render(){ return( <h2>姓名:{this.props.person.name}</h2> ) } }
class App extends Component { constructor(props) { super(props); this.state = { num:0, title:‘react shouldComponentUpdate study‘, } this.handleClick = this.handleClick.bind(this); } handleClick(){ this.setState({ num:this.state.num+1 }) } render() { const _this = this; return ( <div classsName="App"> <h2>App,{this.state.num}</h2> <button onClick={this.handleClick}>btn0</button> <Demo title={this.state.title}></Demo> </div> ) } } export default App; class Demo extends Component{ shouldComponentUpdate(nextProps){ //加了这段代码更新num值不会渲染这个组件,否则就会渲染 if(nextProps.title===this.props.title){ return false; } } render(){ console.log("demo 执行中") return( <h2>demo,{this.props.title}</h2> ) } }
原文:https://www.cnblogs.com/zhangyaolan/p/11072501.html