React 获取服务器的数据 ajax
- axios cros 跨域
安装模块npm install axios --save/cnpm install axios --save
引入模块import axios from ‘axios’
import React,{Component} from 'react';
import Axios from 'axios';//引入请求服务器的模块
componentDidMount(){
let api="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20";
//里面是用this 注意this的指向
Axios.get(api).then( (res)=>{
console.log(res);
}).catch( (err)=>{
console.log(err);
}).finally(()=>{//最终执行操作
});
}
- fetch jsonp 跨域
安装模块npm install fetch-jsonp --save/cnpm install fetch-jsonp --save
引入模块import Fetchjsonp from ‘fetch-jsonp ’
componentDidMount(){
let api="http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20";
fetchjsonp(api).then( (res)=>{ //这里对数据进行操作 默认的
return res.json();
}).then( (res)=>{
console.log(res);
}).catch( (err)=>{
console.log(err);
});
}
React 生命周期函数
组件挂载 >>> 组件数据更新 >>> 组件销毁
componentWillMount(){
console.log("组件挂载之前");
}
componentDidMount(){
console.log("组件挂载完成");
}
//是否更新数据的生命周期函数 返回Boolean 返回true更新
shouldComponentUpdate(){
return true;
}
//将要更新数据的函数
componentWillUpdate(){
console.log("数据更新之前");
}
//数据更新完成
componentDidUpdate(){
console.log("数据更新完成");
}
//组件销毁的时候执行的生命周期函数
componentWillUnmount(){
console.log("组件卸载");
}
React 路由
安装路由 cnpm install react-router-dom –save
安装url模块 cnpm install url –save
解析get传值路由url.parse(this.props.location.search,true).query
// 1.要在项目里面使用路由先导入路由
import {BrowserRouter as Router, Route,Link} from 'react-router-dom';
//2.导入路由子组件
import Home from './component/Home'
import News from './component/News'
import Product from './component/Product'
import Child1 from './component/Product/child1'
//3.3编程式导航
back(){ //路由回退
this.props.history.go(-1));
}
gohome(){//路由回首页
console.log(this.props);
//编程式导航
this.props.history.push("/");
this.props.history.push("/",10); //传值到this.props.location.state
this.props.history.replace("/",20);//传值
}
//3.动态路由传值 get传值
render(){
let match=this.props.match.path;//当前路由
return(
<div>
<Router>
//3.1路由入口
<link to="/">Home</link>
//动态路由传值到 this.props.match.params.id
<link to="/News/:id">News </link>
//get传值 相当于在路径上加?id=1 导入node的url模块进行解析
//get传值到 url.parse(this.props.location.search,true).query
<Link to={`/News?id=${value.id}`}>{value.title}</Link>
<link to="/Product">Product</link>
<link to={`${match}/child1`}>Child1</link> //let match=this.props.match.path;
//3.2路由Route
<Switch>
<Route exact path="/" compoent={Home}></Route> //严格模式
<Route path="/News" compoent={News}></Route>
<Route path="/Product" compoent={Product}></Route>
<Route path={`${match}/child1`} compoent={Child1}></Route>
//重定向 默认child1
<Redirect path={`${match}`} to={`${match}/child1`}></Redirect>
</Switch>
</Router>
//3.3编程式导航 回退 首页
<button onClick={this.back.bind(this)}>路由回退</button>
<button onClick={this.gohome.bind(this)}>回到首页</button>
</div>)}
React Material UI 组件
npm安装npm install @material-ui/core
yarn安装yarn add @material-ui/core