React学习:生命周期、过滤器、event、axios-学习笔记 ﹏ヽ暗。殇╰゛Y 2022-09-02 00:54 101阅读 0赞 ### 文章目录 ### * * React学习:生命周期、过滤器、event、axios-学习笔记 * * 生命周期 * 过滤器 * webapp小例子: * event - 和原生JavaScript写法一样的 * axios ## React学习:生命周期、过滤器、event、axios-学习笔记 ## ### 生命周期 ### ![在这里插入图片描述][watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hoaG1vbmtleQ_size_16_color_FFFFFF_t_70] 组件的生命周期可分成三个状态: * Mounting:已插入真实 DOM(挂载) * Updating:正在被重新渲染(更新) * Unmounting:已移出真实 DOM(卸载) **Mounting** `componentWillMount()` 组件将要挂载 `componentDidMount()` 组件完成挂载 **Updating** `componentWillReceiveProps()` 组件将要接收prop,这个方法在初始化render时不会被调用。 `shouldComponentUpdate()` 返回一个布尔值,在组件接收到新的props或者state时被调用。在初始化时不被调用,减少重复渲染 可以在你确认不需要更新组件时使用。 `componentWillUpdate()` 在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。 `render()` 渲染 `componentDidUpdate()` 在组件完成更新后立即调用。在初始化时不会被调用。Unmounting `componentWillUnmount()` 在组件从 DOM 中移除的时候立刻被调用 **Error Handling** `componentDidCatch()` 错误处理 <!DOCTYPE html> <html> <head> <title>生命周期</title> <meta charset="UTF-8" /> <script src="js/react.development.js"></script> <script src="js/react-dom.development.js"></script> <script src="js/babel.min.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> class Hello extends React.Component{ constructor() { super(); this.state = { data: 0 }; }; setNum(){ this.setState({ data:++this.state.data}) } render () { console.log('1-hello---render'); return ( <div> <button onClick={ () => this.setNum()}>ADD</button> <p>{ this.state.data}</p> <Num myNum={ this.state.data}/> </div> ); } }; class Num extends React.Component{ componentWillMount(){ console.log('2-组件将要挂载'); }; componentDidMount () { console.log('4-组件完成挂载'); }; // shouldComponentUpdate(nextProps,nextState){ // console.log('在组件接收到新的props或者state时被调用'); // if(条件){ // return false; // }else { // return true; // } // } componentWillUpdate() { console.log('组件将要更新-在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。'); }; componentDidUpdate(){ console.log('在组件完成更新后立即调用。在初始化时不会被调用'); } render () { console.log('3-num---render'); return ( <div> <p>{ this.props.myNum}</p> </div> ); } }; ReactDOM.render( <Hello/>, document.getElementById('example') ); </script> </body> </html> <!DOCTYPE html> <html> <head> <title>生命周期2</title> <meta charset="UTF-8" /> <script src="js/react.development.js"></script> <script src="js/react-dom.development.js"></script> <script type="text/javascript" src="js/babel.min.js"></script> </head> <body> <div id="my"></div> <script type="text/babel"> window.onload = function(){ //父组件 class ParentList extends React.Component{ constructor(){ super(); this.state = { name:'老张', age:50 } }; handleChange(e){ this.setState({ age:e.target.value}) } handleParent(child){ //alert(child); this.setState({ age:child}) } render(){ console.log('1-render') return ( <div> <h1>我是父组件</h1> <p>姓名:{ this.state.name}</p> <p>年龄:{ this.state.age}</p> <input type="text" value={ this.state.age} onChange={ (event)=>this.handleChange(event)} /> <ChildList { ...this.state} handleParent={ this.handleParent.bind(this)}/> </div> ) } }; // 子组件 class ChildList extends React.Component{ constructor(props){ super(); this.state = { name:'小张', //age:props.age age:20 } }; componentWillMount(){ console.log('2-组件将要挂载'); }; componentDidMount () { console.log('4-组件完成挂载'); }; componentWillReceiveProps(nextProps){ console.log('update1-组件将要接收prop,这个方法在初始化render时不会被调用。'); } shouldComponentUpdate(nextProps,nextState){ console.log('update2-在组件接收到新的props或者state时被调用'); //在render函数调用前判断 如果 state中的值不变 通过return false阻止render调用 if(nextProps.age == this.state.age){ //nextProps 获取最新props的值 return true //满足了条件 才会执行组件更新钩子函数 }else { return false //false阻止render调用 } } componentWillUpdate() { console.log('update3-组件将要更新-在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。'); }; componentDidUpdate(){ console.log('update5-在组件完成更新后立即调用。在初始化时不会被调用'); } handleChange(e){ this.setState({ age:e.target.value}); this.props.handleParent(e.target.value); } render(){ console.log('3-render====update4-render') return ( <div> <h1>我是子组件</h1> <p>爸爸的姓名:{ this.props.name}</p> <p>爸爸的年龄:{ this.props.age}</p> <p>我的年龄:{ this.state.age}</p> <input type="text" value={ this.state.age} onChange={ (event)=>this.handleChange(event)} /> </div> ) } }; ReactDOM.render( <div> <ParentList></ParentList> </div>, document.getElementById("my") ); } </script> </body> </html> <!DOCTYPE html> <html> <head> <title>生命周期3</title> <meta charset="UTF-8" /> <script src="js/react.development.js"></script> <script src="js/react-dom.development.js"></script> <script src="js/babel.min.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> class Hello extends React.Component{ constructor() { super(); this.timer = null; //定时器 this.state = { opacity: 1 }; }; componentDidMount () { console.log('4-组件完成挂载'); this.timer = setInterval(()=>{ var a = this.state.opacity; a-=0.05; if(a<0.1){ a = 1; }; this.setState({ opacity:a}) },200) }; componentWillUnMount(){ console.log('销毁'); clearInterval(this.timer); } render () { return ( <div> <h1 style={ { opacity:this.state.opacity}}>hello world</h1> </div> ); } }; ReactDOM.render( <Hello/>, document.getElementById('example') ); </script> </body> </html> ### 过滤器 ### <!DOCTYPE html> <html> <head> <title>过滤器filter</title> <meta charset="UTF-8" /> <script src="js/react.development.js"></script> <script src="js/react-dom.development.js"></script> <script src="js/babel.min.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> class Hello extends React.Component{ constructor() { super(); this.state = { date: 1595426683 }; }; getDate(date){ var d=new Date(date*1000); return d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate(); } render () { return ( <div> <h1>北京时间:{ this.getDate(this.state.date)}</h1> </div> ); } }; ReactDOM.render( <Hello/>, document.getElementById('example') ); </script> </body> </html> <!DOCTYPE html> <html> <head> <title>过滤器</title> <meta charset="UTF-8" /> <script src="js/react.development.js"></script> <script src="js/react-dom.development.js"></script> <script src="js/babel.min.js"></script> <style> .lists { color:#f60; } </style> </head> <body> <div id="example"></div> <script type="text/babel"> class HelloMessage extends React.Component{ constructor() { super(); this.state = { value: '' }; }; getDate(data){ var d = new Date(data*1000); return d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate(); } action(item){ if(item>25){ return '到了结婚年龄喽' }else { return '还年轻着呢' } }; action2(item){ switch(item){ case "1": return "启动"; case "2": return "离线"; case "3": return "连接"; default: return item; } } // 输入的内容长度大于多少出现省略号 toShortShow(data,n){ if(!data) return; if(data.length >= n){ var s = data.substr(0,n); return s+'...'; }else { return data; } } handleChange(event){ this.setState({ value:event.target.value}) }; render(){ const user = { name:'lili', age:22, n:'1' }; return ( <div> <h1>北京时间:{ this.getDate('1595426683')}</h1> <h1 className="lists">hello,{ this.action(user.age)}</h1> <h1 className="lists">hello,{ this.action2(user.n)}</h1> <input type="text" value={ this.state.value} onChange={ (event)=>this.handleChange(event)}/> <h1>{ this.toShortShow(this.state.value,5)}</h1> </div> ) } }; ReactDOM.render( <HelloMessage/>, document.getElementById('example') ); </script> </body> </html> ### webapp小例子: ### <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>webapp首页</title> <link rel="stylesheet" type="text/css" href="css/common.css"> <link rel="stylesheet" href="font/iconfont.css"> <script src="js/react.development.js"></script> <script src="js/react-dom.development.js"></script> <script type="text/javascript" src="js/babel.min.js"></script> <body> <!--页面容器--> <div class="index-content" id="my"></div> <script type="text/babel"> window.onload = function(){ class App extends React.Component{ render () { return ( <div> <Banner /> <Category /> </div> ); } }; class Banner extends React.Component{ constructor() { super(); this.timer = null; this.state = { n:0, //初始化 img:['img/1.jpg','img/2.jpg','img/3.jpg','img/4.jpg','img/5.jpg'], }; }; componentDidMount () { //挂载完成 this.autoPlay(); }; autoPlay(){ this.timer = setInterval(()=>{ this.play(); },2000) }; play(){ let { n,img} = this.state; n++; if(n==img.length){ n = 0; }; this.setState({ n //n:n }) }; componentWillUnMount(){ //销毁 console.log('销毁'); clearInterval(this.timer); } render () { let { n,img} = this.state; var imgList = img.map((item,i)=>{ return <img key={ i} src={ item} style={ { display:(i==n)?'block':'none'}}/> }); var liList = img.map((item,i)=>{ return <li key={ i} className={ i==n?"selected":""}></li> }); return ( <div className="banner"> { imgList} <div className="banner-circle"> <ul> { liList} </ul> </div> </div> ); } }; class Category extends React.Component{ constructor() { super(); this.state = { lists:[ { title:'在线咨询1',icon:'icon-shenghuo',color:'#f60'}, { title:'在线咨询2',icon:'icon-shenghuo',color:'#49dacf'}, { title:'在线咨询3',icon:'icon-jiaoyu',color:'#fa6900'}, { title:'在线咨询4',icon:'icon-shenghuo',color:'#49dacf'}, { title:'在线咨询5',icon:'icon-jiajujiafang',color:'#f60'}, { title:'在线咨询6',icon:'icon-shenghuo',color:'#49dacf'}, { title:'在线咨询7',icon:'icon-11',color:'#f00'} ] }; }; render () { let { lists} = this.state; var _list = lists.map((item,i)=>{ return ( <div className="category" key={ i}> <i className={ [`iconfont ${ item.icon}`]} style={ { background:item.color}}></i> <label>{ item.title}</label> </div> ) }) return ( <div className="index-category"> { _list} </div> ); } }; ReactDOM.render( <App />, document.getElementById("my") ) } </script> </body> </html> common.js *{ margin:0; padding:0; } ul { list-style-type:none; } body { font-size: 14px; background: #fff; overflow-y:scroll; overflow-x:hidden; } html,body { max-width:720px; height:100%; margin:0 auto; } /*index*/ .index-content .banner { position: relative; } .index-content .banner .banner-circle { position: absolute; bottom: 5px; left: 0; right: 0; color: #fff; } .index-content .banner .banner-circle li{ display:inline-block; background: rgba(0,0,0,.3); border-radius: 50%; padding:7px; margin:2px; } .index-content .banner .banner-circle ul { text-align: center; } .index-content .banner .banner-circle .selected { background: #f60; } .index-content .banner img { width: 100%; margin: 0; padding: 0; } /*index-category*/ .index-content .index-category .category { width: 33.3%; float:left; padding: 17px 0; text-align:center; border-bottom: 1px solid #f0f0f0; } .index-content .index-category .category .iconfont { font-size: 40px; display:inline-block; padding: 10%; border-radius: 50%; color:#fff; border: 3px solid #f9f9f9; box-shadow: 0px 0px 6px rgba(0,0,0,.5); } .index-content .index-category .category .iconfont{ background: #49dacf; } .index-content .index-category .category label { display: block; padding: 5px 0; color: #999; } /*index-category end*/ 字体图标可见下文有提到iconfont: [https://blog.csdn.net/hhhmonkey/article/details/118657708][https_blog.csdn.net_hhhmonkey_article_details_118657708] ### event - 和原生JavaScript写法一样的 ### <!DOCTYPE html> <html> <head> <title>event</title> <meta charset="UTF-8" /> <script src="js/react.development.js"></script> <script src="js/react-dom.development.js"></script> <script src="js/babel.min.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> class TabList extends React.Component{ constructor() { super(); }; setParent(e) { console.log('parent'); }; setChild(e) { console.log('child'); e.stopPropagation(); //阻止冒泡 }; setOpen(e) { console.log('open'); e.stopPropagation(); //阻止冒泡 e.preventDefault() ; //取消事件默 认行为 } render () { return( <div onClick={ (event) => this.setParent(event)}>parent <button onClick={ (event) => this.setChild(event)}>child</button> <a href="www.baidu.com" onClick={ (event) => this.setOpen(event)}>open</a> </div> ) } }; ReactDOM.render( <TabList />, document.getElementById('example') ); </script> </body> </html> ### axios ### <!DOCTYPE html> <html> <head> <title>ajax</title> <meta charset="UTF-8" /> <script src="js/react.development.js"></script> <script src="js/react-dom.development.js"></script> <script src="js/babel.min.js"></script> <script src="js/axios.js"></script> </head> <body> <div id="example"></div> <script type="text/babel"> class TabList extends React.Component{ constructor() { super(); this.state = { result:[], name:'', select:'red' }; }; componentDidMount () { // this.handleChange(); }; handleChange(){ axios({ method:'get', url:'http://localhost:3333/get_table' }).then(response=>{ if(response.data.code=='200'){ this.setState({ result:response.data.result}) } }).catch(function(error){ console.log(error); }) } handleChange2(e){ var name = e.target.name; this.setState({ [name]:e.target.value }) } submit(){ var { name,select} = this.state; axios({ method:'post', url:'http://localhost:3333/form_register', data:JSON.stringify({ name:name,select:select}) }).then(response=>{ if(response.data.code=='200'){ console.log('ok') } }).catch(function(error){ console.log(error); }) } render () { let color = ['red','blue','green']; return( <div> <button onClick={ (event)=>this.handleChange(event)}>click</button> <ul> { this.state.result.map(function(item,index){ return <li key={ index}>{ item.name}-{ item.city}</li> }) } </ul> <div> name:<input type='text' name='name' value={ this.state.name} onChange={ (event)=>this.handleChange2(event)} /> color: <select name='select' value={ this.state.select} onChange={ (event)=>this.handleChange2(event)} > { color.map((item,index)=>{ return <option key={ index}>{ item}</option> }) } </select> <button onClick={ ()=>this.submit()}>提交</button> </div> </div> ) } }; ReactDOM.render( <TabList />, document.getElementById('example') ); </script> </body> </html> [watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2hoaG1vbmtleQ_size_16_color_FFFFFF_t_70]: /images/20220829/8615d8b906f74c8988a0aa7f2f7504be.png [https_blog.csdn.net_hhhmonkey_article_details_118657708]: https://blog.csdn.net/hhhmonkey/article/details/118657708
还没有评论,来说两句吧...