React简介:起源于Facebook内部项目,用于架设INS的网站,13年5月份开源。
1 HTML模板
首先script标签的type
属性必须为text/babel
,属于JSX语法,需要用到三个库,react.development.js
(React的核心库) react-dom.development.js
和babel.min.js
浏览器中使用babel编译JSX效率是非常低的
2 render
每个组件都必须有的方法,用于渲染,React
支持组件开发,组件之间的数据交互使用props
和state
,props
指不可更改的属性,state
用于可以改变的数据,用setState
改变值
3 生命周期函数
React中生命周期函数有三种状态
Mounting
加载
Updating
更新
Unmounting
关闭
React的七个生命周期函数
componentWillMount
组件将要被渲染 常用于使用Ajax请求时
componentDidMount
组件被渲染以后
componentWillReceiveProps
组件将要接收props和state
componentDidUpdate
组件被更新之后
componentWillUpdate
组件将要被更新
componentWillUnmount
组件将要被关闭
shouldComponentUpdate
组件是否需要被更新,返回true就更新,false就不更新
示例
// AJAX
componentWillMount() {
console.log("componentWillMount");
}
// 添加动画
componentDidMount() {
console.log("componentDidMount");
}
// 将要接收props/state数据
componentWillReceiveProps() {
console.log("componentWillReceiveProps");
}
// 更新之后
componentDidUpdate() {
console.log("componentDidUpdate");
}
// 将要更新
componentWillUpdate() {
console.log("componentWillUpdate");
}
// 将要被卸载
componentWillUnmount() {
console.log("componentUnmount");
}
shouldComponentUpdate() {
console.log("shouldComponentUpdate");
if (this.state.msg === "helloworld") {
return true;
} else {
return false;
}
}
4 Ajax请求
Ajax请求会返回一个promise
对象,所以必须加await
。
async componentWillMount() {
let res = await axios.get('http://localhost:8080/api/newsdata');
let data = res.data;
let jsondata = JSON.parse(data.forum.extra.ncov_string_list);
let newsdata = jsondata.provinces;
let newsdataSort = newsdata.sort((a, b) => {
if(a.confirmedNum > b.confirmedNum) {
return -1
} else {
return 1
}
})
this.setState({
newsdata: newsdataSort
})
}