目录
一、Redux
(1)Redux基本认识
我们为什么需要状态管理器Redux?为了方便的组织和管理组件之间的数据。
Redux是一个流行的JavaScript框架,为应用程序提供一个可预测的状态容器。Redux基于简化版本的Flux框架,Flux是Facebook开发的一个框架。在标准的MVC框架中,数据可以在UI组件和存储之间双向流动,而Redux严格限制了数据只能在一个方向上流动。
Store:存储数据的公告区域;eg--图书管理员;
React Component:页面组件;eg--借书的用户;
Reducer:数据存放位置;eg--图书记录本;
Action Creators:动作;eg--结束的时候,跟图书管理员说的话;
-
Redux基本原则
-
单一数据源;
-
state是只读的;
-
使用纯函数来执行修改;
-
-
Redux核心API
-
createStore(reducer):创建数据仓库: import {createStore} from "redux";
-
store.getState():用于获取store里面的数据;
-
store.dispatch(action):用于派发action,触发reducer,执行修改动作;
-
store.subscribe(componentMethods):订阅store的修改,只要store发生改变,组件中的回调函数就会被执行;
-
(2)store的创建和使用
1、使用Redux需要安装该模块
cnpm i redux –save
2、创建reducer(store/reducer.js),提供数据源,是一个纯函数
// src/store/reducer.js
const defaultState = {
username: "小明",
stulist: ['a', 'b', 'c']
}
2.1、state用于提供为仓库提供数据源,需要给定一个初始值
2.2、action用于对state 进行更新处理,表示要执行的动作,通过dispatch(action)触发;action被传递到reducer内部来处理,action中必须有一个type字段
// src/store/reducer.js
const reducer = (state=defaultState) => {
//action……
return state;//必须返回处理后的state
}
export default reducer;
- 创建数据仓库(store/index.js):createStore()
```react
// src/store/index.js
import {createStore} from "redux";
import reducer from "./reducer";
const store = createStore(reducer);
export default store;
3、组件内部使用数据:getState()
//组件内部引入仓库
import store from "./store/index";
//获取数据
<h2>{store.getState().username}</h2>
(3)数据的修改和订阅
1、在组件内部定义要执行的动作action,并触发该动作dispatch。
action中type字段是必须的,值通常大写:
addValue() {
const action = {
type: "ADD",
data: "测试数据"
}
store.dispatch(action);
}
2、接收动作并修改数据:通过dispatch触发动作后,会将action传递到reducer函数的第二个参数中
const reducer = (state=defaultState, action) => {
switch(action.type) {
case "ADD":
state.stulist.push(action.data);
break;
default:
break;
}
return state;
}
3、组件中及时响应更新的数据:订阅
componentDidMount() {
// 订阅store改变事件
store.subscribe(this.changeValue.bind(this));
}
changeValue() {
this.setState(store.getState())
}
subscribe函数可以监听Redux中state的变化,一旦Redux中的state发生了变化,render函数就会被调用,页面就会被重新渲染
二、ant Design
蚂蚁金服(antd)不仅Reac有,Vue也有
(1)全量引入方式
官网:Ant Design of React - Ant Design
1.npm 安装
$ npm install antd --save
2.示例
import { DatePicker,Button } from 'antd';
ReactDOM.render(
<div>
<DatePicker />
<Button type="primary">ant按钮</Button>
</div>
, mountNode);
引入样式
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
(2)按需加载
import DatePicker from 'antd/lib/date-picker'; // 加载 JS
import 'antd/lib/date-picker/style/css'; // 加载 CSS
import Button from 'antd/lib/button'; // 加载 JS
import 'antd/lib/button/style/css'; // 加载 CSS
(3)组件API
我们学过的每一个UI框架都有它自己的组件编码风格,只要按照api标准编程即可