生命周期流程图
生命周期详述
-
组件的三个生命周期状态:
* Mount:插入真实 DOM
* Update:被重新渲染
* Unmount:被移出真实 DOM
-
React 为每个状态都提供了勾子(hook)函数
* componentWillMount()
* componentDidMount()
* componentWillUpdate()
* componentDidUpdate()
* componentWillUnmount()
-
生命周期流程:
- 第一次初始化渲染显示: ReactDOM.render()
* constructor(): 创建对象初始化state
* componentWillMount() : 将要插入回调在render的前一步触发 (更新前)
* render() : 用于插入虚拟DOM回调
* componentDidMount() : 已经插入回调 (更新完毕了,相当于vue的mounted uni-app的onLode)
- 每次更新state: this.setSate()
* componentWillUpdate() : 将要更新回调
* render() : 更新数据(重新渲染) 时都回调用
* componentDidUpdate() : 已经更新回调
- 移除组件: ReactDOM.unmountComponentAtNode(“要删除的节点里面的组件比如#app”)
* componentWillUnmount() : 组件将要被移除回调
重要的勾子
-
render(): 初始化渲染或更新渲染调用
-
componentDidMount(): 开启监听, 发送ajax请求 相当于onlode() dom加载完毕后执行
-
componentWillUnmount(): 做一些收尾工作, 如: 清理定时器
-
componentWillReceiveProps(): 后面需要时讲
react 脚手架
创建项目并启动
- 全局安装react脚手架
npm install -g create-react-app
- 创建项目及项目名
create-react-app hello-react
cd hello-react
- 运行
npm start
react脚手架项目结构
ReactNews
|–node_modules—第三方依赖模块文件夹
|–public
|– *index.html-----------------*主页面
|–scripts
|– build.js-------------------build**打包引用配置
|– start.js-------------------start**运行引用配置
|–src------------源码文件夹
|–components-----------------react**组件
|–index.js-------------------应用入口js
|–.gitignore------git版本管制忽略的配置
|–package.json----应用包配置文件
|–README.md-------应用描述说明的readme文件
路由
- 下载
npm install --save react-router-dom
基本使用
index.js
import React from 'react'
import {render} from 'react-dom'
import {BrowserRouter} from 'react-router-dom'
import App from './components/App.js'
render(
(
<BrowserRouter>
<App />
</BrowserRouter>
),document.getElementById('root')
)
App.js
//引用react
import React ,{Component}from 'react'
//引用react-router 路由组件
import {NavLink,Switch,Route,Redirect} from 'react-router-dom'
//引用定义好的组件
import Home from './Home.js'
import About from './about.js'
export default class App extends Component{
render() {
return(
<div>
<p>
{ /*NavLink 相当于vue的 view-lick */ }
<NavLink to="/Home">Home</NavLink>
</p>
<p>
<NavLink to="/about">about</NavLink>
</p>
{ /* Switch 坑中坑 用来存放多个坑 */ }
<Switch>
{ /* Route 给组件留的坑 */ }
<Route path="/Home" component={Home}/>
<Route path="/about" component={About}/>
{ /* Redirect 默认显示坑中的那个组件 */ }
<Redirect to="/about" />
</Switch>
</div>
)
}
}
about.js 组件
import React,{Component} from 'react'
export default class About extends Component{
render() {
return (
<h1>我是路由about的组件</h1>
)
}
}
路由组件传递数据
父路由
render() {
let arr = [
{
id:1,
title:"abcd1",
text:"巴拉巴拉巴拉1"
},
{
id:2,
title:"abcd2",
text:"巴拉巴拉巴拉2"
},
{
id:3,
title:"abcd3",
text:"巴拉巴拉巴拉3"
},
{
id:4,
title:"abcd4",
text:"巴拉巴拉巴拉4"
}
]
return (
<div>
<h3>home的子组件HomeChild2</h3>
<ul>
{
arr.map( (itme,index) =>
<li key={index}><MyNavLink to={`/Home/homeChild2/${itme.id}`}>{itme.title}</MyNavLink></li>
)
}
</ul>
<Switch>
//:id 用来存储上面/Home/homeChild2/后的参数
//在List路由中可以通过this.props.match.params.id来获取
<Route path="/Home/homeChild2/:id" component={List}/>
</Switch>
</div>
)}
子 List路由
render() {
let arr = [
{
id:1,
title:"abcd1",
text:"巴拉巴拉巴拉1"
},
{
id:2,
title:"abcd2",
text:"巴拉巴拉巴拉2"
},
{
id:3,
title:"abcd3",
text:"巴拉巴拉巴拉3"
},
{
id:4,
title:"abcd4",
text:"巴拉巴拉巴拉4"
}
]
// 通过this.props.match.params来获取传过来的数据
var id = (this.props.match.params.id) - 1;
return (
<div>
<ul>
<li>{ arr[id].id }</li>
<li>{ arr[id].title }</li>
<li>{ arr[id].text }</li>
</ul>
</div>
)
}
最流行的开源React UI组件库
material-ui(国外)
官网: http://www.material-ui.com/#/
github: https://github.com/callemall/material-ui
ant-design(国内蚂蚁金服)
PC官网: https://ant.design/index-cn
移动官网: https://mobile.ant.design/index-cn
Github: https://github.com/ant-design/ant-design/
Github: https://github.com/ant-design/ant-design-mobile/
ant-design使用
安装#
$ npm install antd-mobile --save
使用#
入口页面 (html 或 模板) 相关设置:
引入 FastClick 并且设置 html
meta
(更多参考 #576)引入 Promise 的 fallback 支持 (部分安卓手机不支持 Promise)
<!DOCTYPE html>
<html>
<head>
<!-- set `maximum-scale` for some compatibility issues -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<script src="https://as.alipayobjects.com/g/component/fastclick/1.0.6/fastclick.js"></script>
<script>
if ('addEventListener' in document) {
document.addEventListener('DOMContentLoaded', function() {
FastClick.attach(document.body);
}, false);
}
if(!window.Promise) {
document.writeln('<script src="https://as.alipayobjects.com/g/component/es6-promise/3.2.2/es6-promise.min.js"'+'>'+'<'+'/'+'script>');
}
</script>
</head>
<body></body>
</html>
组件使用实例:
import { Button } from 'antd-mobile';
ReactDOM.render(<Button>Start</Button>, mountNode);
引入样式:
import 'antd-mobile/dist/antd-mobile.css'; // or 'antd-mobile/dist/antd-mobile.less'
ant-design实现按需打包(组件js/css)
下载依赖包
- npm 安装好像快 一点
yarn add react-app-rewired --dev
yarn add babel-plugin-import --dev
修改默认配置:
- package.json
"scripts": {
"start": "react-app-rewired start",
"build": "react-app-rewired build",
"test": "react-app-rewired test --env=jsdom"
}
在根目录新建
config-overrides.js
- config-overrides.js
const {injectBabelPlugin} = require('react-app-rewired');
module.exports = function override(config, env) {
config = injectBabelPlugin(['import', {libraryName: 'antd-mobile', style: 'css'}], config);
return config;
};
- 使用
只需从 antd-mobile 引入模块即可,无需单独引入样式
// import 'antd-mobile/dist/antd-mobile.css'
// import Button from 'antd-mobile/lib/button'
// import Toast from 'antd-mobile/lib/toast'
//主用
import {Button, Toast} from 'antd-mobile'
redux
redux理解
学习文档
-
英文文档: https://redux.js.org/
-
中文文档: http://www.redux.org.cn/
-
Github: https://github.com/reactjs/redux
redux是什么?
-
redux是一个独立专门用于做状态管理的JS库(不是react插件库)
-
它可以用在react, angular, vue等项目中, 但基本与react配合使用
-
作用: 集中式管理react应用中多个组件共享的状态
redux工作流程
[外链图片转存失败(img-1c75Drzd-1569061704817)(img/clip_image002.jpg)]
什么情况下需要使用redux
-
总体原则: 能不用就不用, 如果不用比较吃力才考虑使用
-
某个组件的状态,需要共享
-
某个状态需要在任何地方都可以拿到
-
一个组件需要改变全局状态
-
一个组件需要改变另一个组件的状态
xredux的核心API
createStore()
-
作用:
创建包含指定reducer的store对象
-
编码:
import {createStore} from ‘redux’
import counter from ‘./reducers/counter’
const store = createStore(counter)
store对象
-
作用:
redux库最核心的管理对象
-
它内部维护着:
state
reducer
-
核心方法:
getState()
dispatch(action)
subscribe(listener)
-
编码:
store.getState()
store.dispatch({type:‘INCREMENT’, number})
store.subscribe(render)
applyMiddleware()
-
作用:
应用上基于redux的中间件(插件库)
-
编码:
import {createStore, applyMiddleware} from ‘redux’
import thunk from ‘redux-thunk’ // redux异步中间件
const store = createStore(
counter,
applyMiddleware(thunk) // 应用上异步中间件
)
combineReducers()
-
作用:
合并多个reducer函数
-
编码:
export default combineReducers({
user,
chatUser,
chat
})
redux的三个核心概念
action
-
标识要执行行为的对象
-
包含2个方面的属性
a. type: 标识属性, 值为字符串, 唯一, 必要属性
b. xxx: 数据属性, 值类型任意, 可选属性
-
例子:
const action = {
type: ‘INCREMENT’,
data: 2
}
-
Action Creator(创建Action的工厂函数)
const increment = (number) => ({type: ‘INCREMENT’, data: number})
reducer
-
根据老的state和action, 产生新的state的纯函数
-
样例
export default function counter(state = 0, action) {
switch (action.type) {
case ‘INCREMENT’:
return state + action.data
case ‘DECREMENT’:
return state - action.data
default:
return state
}
}
-
注意
a. 返回一个新的状态
b. 不要修改原来的状态
store
-
将state,action与reducer联系在一起的对象
-
如何得到此对象?
import {createStore} from ‘redux’
import reducer from ‘./reducers’
const store = createStore(reducer)
-
此对象的功能?
getState(): 得到state
dispatch(action): 分发action, 触发reducer调用, 产生新的state
使用redux编写应用
下载依赖包
npm install --save redux
redux/action-types.js
- 定义函数名
/*
action对象的type常量名称模块
*/
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
redux/actions.js
/*
action creator模块
*/
import {INCREMENT, DECREMENT} from './action-types'
export const increment = number => ({type: INCREMENT, number})
export const decrement = number => ({type: DECREMENT, number})
redux/reducers.js
/*
根据老的state和指定action, 处理返回一个新的state
*/
import {INCREMENT, DECREMENT} from './action-types'
export function counter(state = 0, action) {
console.log('counter', state, action)
switch (action.type) {
case INCREMENT:
return state + action.number
case DECREMENT:
return state - action.number
default:
return state
}
}
components/app.jsx
- 调用方法传递参数
this.props.store.dispatch(actions.increment(number))
/*
应用组件
*/
import React, {Component} from 'react'
import PropTypes from 'prop-types'
import * as actions from '../redux/actions'
export default class App extends Component {
static propTypes = {
store: PropTypes.object.isRequired,
}
increment = () => {
const number = this.refs.numSelect.value * 1
this.props.store.dispatch(actions.increment(number))
}
decrement = () => {
const number = this.refs.numSelect.value * 1
this.props.store.dispatch(actions.decrement(number))
}
incrementIfOdd = () => {
const number = this.refs.numSelect.value * 1
let count = this.props.store.getState()
if (count % 2 === 1) {
this.props.store.dispatch(actions.increment(number))
}
}
incrementAsync = () => {
const number = this.refs.numSelect.value * 1
setTimeout(() => {
this.props.store.dispatch(actions.increment(number))
}, 1000)
}
render() {
return (
<div>
<p>
click {this.props.store.getState()} times {' '}
</p>
<select ref="numSelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>{' '}
<button onClick={this.increment}>+</button>
{' '}
<button onClick={this.decrement}>-</button>
{' '}
<button onClick={this.incrementIfOdd}>increment if odd</button>
{' '}
<button onClick={this.incrementAsync}>increment async</button>
</div>
)
}
}
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import {createStore} from 'redux'
import App from './components/app'
import {counter} from './redux/reducers'
// 根据counter函数创建store对象
const store = createStore(counter)
// 定义渲染根组件标签的函数
const render = () => {
ReactDOM.render(
<App store={store}/>,
document.getElementById('root')
)
}
// 初始化渲染
render()
// 注册(订阅)监听, 一旦状态发生改变, 自动重新渲染
store.subscribe(render)
问题
-
redux与react组件的代码耦合度太高
-
编码不够简洁
react-redux
8.5.1. 理解
-
一个react插件库
-
专门用来简化react应用中使用redux
8.5.2. React-Redux将所有组件分成两大类
-
UI组件
a. 只负责 UI 的呈现,不带有任何业务逻辑
b. 通过props接收数据(一般数据和函数)
c. 不使用任何 Redux 的 API
d. 一般保存在components文件夹下
-
容器组件
a. 负责管理数据和业务逻辑,不负责UI的呈现
b. 使用 Redux 的 API
c. 一般保存在containers文件夹下
8.5.3. 相关API
-
Provider
让所有组件都可以得到state数据
-
connect()
用于包装 UI 组件生成容器组件
import { connect } from ‘react-redux’
connect(
mapStateToprops,
mapDispatchToProps
)(Counter)
-
mapStateToprops()
将外部的数据(即state对象)转换为UI组件的标签属性
const mapStateToprops = function (state) {
return {
value: state
}
}
-
mapDispatchToProps()
将分发action的函数转换为UI组件的标签属性
简洁语法可以直接指定为actions对象或包含多个action方法的对象
8.5.4. 使用react-redux
-
下载依赖包
npm install --save react-redux
-
redux/action-types.js
不变
-
redux/actions.js
不变
-
redux/reducers.js
不变
-
components/counter.jsx
/*
UI组件: 不包含任何redux API
*/
import React from 'react'
import PropTypes from 'prop-types'
export default class Counter extends React.Component {
static propTypes = {
count: PropTypes.number.isRequired,
increment: PropTypes.func.isRequired,
decrement: PropTypes.func.isRequired
}
increment = () => {
const number = this.refs.numSelect.value * 1
this.props.increment(number)
}
decrement = () => {
const number = this.refs.numSelect.value * 1
this.props.decrement(number)
}
incrementIfOdd = () => {
const number = this.refs.numSelect.value * 1
let count = this.props.count
if (count % 2 === 1) {
this.props.increment(number)
}
}
incrementAsync = () => {
const number = this.refs.numSelect.value * 1
setTimeout(() => {
this.props.increment(number)
}, 1000)
}
render() {
return (
<div>
<p>
click {this.props.count} times {' '}
</p>
<select ref="numSelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>{' '}
<button onClick={this.increment}>+</button>
{' '}
<button onClick={this.decrement}>-</button>
{' '}
<button onClick={this.incrementIfOdd}>increment if odd</button>
{' '}
<button onClick={this.incrementAsync}>increment async</button>
</div>
)
}
}
-
containters/app.jsx
/*
包含Counter组件的容器组件
*/
import React from 'react'
// 引入连接函数
import {connect} from 'react-redux'
// 引入action函数
import {increment, decrement} from '../redux/actions'
import Counter from '../components/counter'
// 向外暴露连接App组件的包装组件
export default connect(
state => ({count: state}),
{increment, decrement}
)(Counter)
-
index.js
import React from 'react'
import ReactDOM from 'react-dom'
import {createStore} from 'redux'
import {Provider} from 'react-redux'
import App from './containers/app'
import {counter} from './redux/reducers'
// 根据counter函数创建store对象
const store = createStore(counter)
// 定义渲染根组件标签的函数
ReactDOM.render(
(
<Provider store={store}>
<App />
</Provider>
),
document.getElementById('root')
8.5.5. 问题
-
redux默认是不能进行异步处理的,
-
应用中又需要在redux中执行异步任务(ajax, 定时器)
8.6. redux异步编程
8.6.1. 下载redux插件(异步中间件)
npm install --save redux-thunk
8.6.2. index.js
import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
// 根据counter函数创建store对象
const store = createStore(
counter,
applyMiddleware(thunk) // 应用上异步中间件
)
8.6.3. redux/actions.js
/*
action creator模块
*/
import {ADD, REDUCE} from './action-types.js'
export const add = number => ({type: ADD, number})
export const reduce = number => ({type: REDUCE, number})
// 异步action creator(返回一个函数)
export const incrementAsync = number => {
return dispatch => {
setTimeout(() => {
// 调用add
dispatch(add(number))
}, 1000)
}
}
8.6.4. components/counter.jsx
incrementAsync = () => {
const number = this.refs.numSelect.value*1
this.props.incrementAsync(number)
}
8.6.5. containers/app.jsx
import {increment, decrement, incrementAsync} from '../redux/actions'
// 向外暴露连接App组件的包装组件
export default connect(
state => ({count: state}),
{increment, decrement, incrementAsync}
)(Counter)
8.7. 使用上redux调试工具
8.7.1. 安装chrome浏览器插件
chrome商店:https://chrome.google.com/webstore/search/redux-devtools?hl=zh-CN
8.7.2. 下载工具依赖包
npm install --save-dev redux-devtools-extension
8.7.3. 编码
import { composeWithDevTools } from 'redux-devtools-extension'
// 根据counter函数创建store对象
const store = createStore(
counter,
composeWithDevTools(applyMiddleware(thunk))
)