React基础知识3

React基础知识3

12.react-ui

12.1 -最流行的开源React UI组件库
a. material-ui(国外)

1.官网: http://www.material-ui.com/#/
2.github: https://github.com/callemall/material-ui

b. ant-design(国内蚂蚁金服)/ANTD

1.PC官网: https://ant.design/index-cn
2.移动官网: https://mobile.ant.design/index-cn
3.Github: https://github.com/ant-design/ant-design/
4.Github: https://github.com/ant-design/ant-design-mobile/

12.2 -ant-design-mobile使用入门
1.使用create-react-app创建react应用

	1.npm install create-react-app -g
	2.create-react-app antm-demo
	3.cd antm-demo
	4.npm start

2.搭建antd-mobile的基本开发环境
1-下载

npm install antd-mobile --save

2-src/App.jsx

import React, {Component} from 'react'
// 分别引入需要使用的组件
import Button from 'antd-mobile/lib/button'
import Toast from 'antd-mobile/lib/toast'
export default class App extends Component {
  handleClick = () => {
    Toast.info('提交成功', 2)
  }
  render() {
    return (
      <div>
        <Button type="primary" onClick={this.handleClick}>提交</Button>
      </div>
    )
  }
}

3- src/index.js

import React from 'react';
import ReactDOM from 'react-dom'
import App from "./App"
// 引入整体css
import 'antd-mobile/dist/antd-mobile.css'
ReactDOM.render(<App />, document.getElementById('root'))

4- index.html

<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>

3.实现按需打包(组件js/css)
1.下载依赖包

yarn add react-app-rewired --dev
yarn add babel-plugin-import --dev

2.修改默认配置:

//package.json
"scripts": {
  "start": "react-app-rewired start",
  "build": "react-app-rewired build",
  "test": "react-app-rewired test --env=jsdom"
}
//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;
};

3.编码

import {Button, Toast} from 'antd-mobile'

13. Redux

13.1 认识redux

文档链接:http://www.redux.org.cn/
       :https://www.reduxjs.cn/introduction/getting-started
1.redux是一个独立专门用于做状态管理的JS(不是react插件库)
2.它可以用在react, angular, vue等项目中, 但基本与react配合使用
3.作用: 集中式管理react应用中多个组件共享的状态

什么情况下需要使用redux?

1   总体原则: 能不用就不用, 如果不用比较吃力才考虑使用
2	某个组件的状态,需要共享
3	某个状态需要在任何地方都可以拿到
4	一个组件需要改变全局状态
5   一个组件需要改变另一个组件的状态

redux工作流程图
在这里插入图片描述

13.2 redux的核心API

1.createStore()
作用:
创建包含指定reducer的store对象
编码:

import {createStore} from 'redux'
import counter from './reducers/counter'
const store = createStore(counter)

2.store对象
作用:
redux库最核心的管理对象,它内部维护着:state与reducer
核心方法:
getState()
dispatch(action)
subscribe(listener)

编码:

store.getState()
store.dispatch({type:'INCREMENT', number})
store.subscribe(render)	

3 . applyMiddleware()
作用:
应用上基于redux的中间件(插件库)
编码:

import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'  // redux异步中间件
const store = createStore(
  counter,
  applyMiddleware(thunk) // 应用上异步中间件
)

4 . combineReducers()
作用:
合并多个reducer函数
编码:

export default combineReducers({
  user,
  chatUser,
  chat
})

13.3 redux的三个核心概念

1 . action

1)标识要执行行为的对象
2)包含2个方面的属性
a.type: 标识属性, 值为字符串, 唯一, 必要属性
b.xxx: 数据属性, 值类型任意, 可选属性
3)例子:
		const action = {
			type: 'INCREMENT',
			data: 2
		}
4)Action Creator(创建Action的工厂函数)
		const increment = (number) => ({type: 'INCREMENT', data: number})		

2 . reducer

1)根据老的state和action, 产生新的state的纯函数
2)样例
		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
		  }
		}
3)注意
a.返回一个新的状态
b.不要修改原来的状态

3 . store

1)将state,action与reducer联系在一起的对象
2)如何得到此对象?
		import {createStore} from 'redux'
		import reducer from './reducers'
		const store = createStore(reducer)
3)此对象的功能?
		getState(): 得到state
		dispatch(action): 分发action, 触发reducer调用, 产生新的state
		subscribe(listener): 注册监听, 当产生了新的state时, 自动调用	

13.4 使用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 '../constants/ActionTypes'
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

/*
应用组件
 */
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)

问题

1)redux与react组件的代码耦合度太高
2)编码不够简洁

13.5 react-redux

理解
1)一个react插件库
2)专门用来简化react应用中使用redux
React-Redux将所有组件分成两大类
1)UI组件

a.只负责 UI 的呈现,不带有任何业务逻辑
b.通过props接收数据(一般数据和函数)
c.不使用任何 Redux 的 API
d.一般保存在components文件夹下

2)容器组件

a.负责管理数据和业务逻辑,不负责UI的呈现
b.使用 Redux 的 API
c.一般保存在containers文件夹下

相关API
1)Provider
让所有组件都可以得到state数据

<Provider store={store}>
    <App />
  </Provider>

2)connect()
用于包装 UI 组件生成容器组件

import { connect } from 'react-redux'
  connect(
    mapStateToprops,
    mapDispatchToProps
  )(Counter)

3)mapStateToprops()
将外部的数据(即state对象)转换为UI组件的标签属性

  const mapStateToprops = function (state) {
   return {
     value: state
   }
  }

4)mapDispatchToProps()
将分发action的函数转换为UI组件的标签属性
简洁语法可以直接指定为actions对象或包含多个action方法的对象

使用react-redux
1)下载依赖包

npm install --save react-redux

2)redux/action-types.js
不变
3)redux/actions.js
不变
4)redux/reducers.js
不变
5)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>
    )
  }
}

6)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)

7)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')

问题

1)redux默认是不能进行异步处理的, 
2)应用中又需要在redux中执行异步任务(ajax, 定时器)

13.6 redux异步编程

下载redux插件(异步中间件)

npm install --save redux-thunk

index.js

import {createStore, applyMiddleware} from 'redux'
import thunk from 'redux-thunk'
// 根据counter函数创建store对象
const store = createStore(
 counter,
 applyMiddleware(thunk) // 应用上异步中间件
)

redux/actions.js

// 异步action creator(返回一个函数)
export const incrementAsync = number => {
  return dispatch => {
    setTimeout(() => {
      dispatch(increment(number))
    }, 1000)
  }
}

components/counter.jsx

incrementAsync = () => {
 const number = this.refs.numSelect.value*1
 this.props.incrementAsync(number)
}

containers/app.jsx

import {increment, decrement, incrementAsync} from '../redux/actions'
// 向外暴露连接App组件的包装组件
export default connect(
  state => ({count: state}),
  {increment, decrement, incrementAsync}
)(Counter)

13.7 使用上redux调试工具

安装chrome浏览器插件
下载解压直接拖入扩展程序界面即可
在这里插入图片描述

下载工具依赖包

npm install --save-dev redux-devtools-extension

编码

import { composeWithDevTools } from 'redux-devtools-extension'
const store = createStore(
  counter,
  composeWithDevTools(applyMiddleware(thunk)) 
)

13.8 相关重要知识: 纯函数和高阶函数

1.纯函数
1.1 一类特别的函数: 只要是同样的输入,必定得到同样的输出
1.2必须遵守以下一些约束
a.不得改写参数
b.不能调用系统 I/O 的API
c.能调用Date.now()或者Math.random()等不纯的方法
1.3reducer函数必须是一个纯函数
2.高阶函数
2.1 理解: 一类特别的函数
a.情况1: 参数是函数
b.情况2: 返回是函数
2.2 常见的高阶函数:
a.定时器设置函数
b.数组的map()/filter()/reduce()/find()/bind()
c.react-redux中的connect函数
2.3作用: 能实现更加动态, 更加可扩展的功能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值