React学习:生命周期、过滤器、event、axios-学习笔记
生活随笔
收集整理的這篇文章主要介紹了
React学习:生命周期、过滤器、event、axios-学习笔记
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- React學習:生命周期、過濾器、event、axios-學習筆記
- 生命周期
- 過濾器
- webapp小例子:
- event - 和原生JavaScript寫法一樣的
- axios
React學習:生命周期、過濾器、event、axios-學習筆記
生命周期
組件的生命周期可分成三個狀態(tài):
- Mounting:已插入真實 DOM(掛載)
- Updating:正在被重新渲染(更新)
- Unmounting:已移出真實 DOM(卸載)
Mounting
componentWillMount() 組件將要掛載
componentDidMount() 組件完成掛載
Updating
componentWillReceiveProps() 組件將要接收prop,這個方法在初始化render時不會被調(diào)用。
shouldComponentUpdate() 返回一個布爾值,在組件接收到新的props或者state時被調(diào)用。在初始化時不被調(diào)用,減少重復渲染 可以在你確認不需要更新組件時使用。
componentWillUpdate() 在組件接收到新的props或者state但還沒有render時被調(diào)用。在初始化時不會被調(diào)用。
render() 渲染
componentDidUpdate() 在組件完成更新后立即調(diào)用。在初始化時不會被調(diào)用。Unmounting
componentWillUnmount() 在組件從 DOM 中移除的時候立刻被調(diào)用
Error Handling
componentDidCatch() 錯誤處理
過濾器
<!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;}}// 輸入的內(nèi)容長度大于多少出現(xiàn)省略號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
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>總結
以上是生活随笔為你收集整理的React学习:生命周期、过滤器、event、axios-学习笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: React学习:组件之间的关系、参数传递
- 下一篇: 将一个数字划分成树状