Redux

203 阅读1分钟

概念:redux = Reducer + Flux

1)Redux Flow:

Store 创建

1、安装yarn add redux 2、src下 创建store ——》 index.js

2)设计的三个原则:

1、store 是唯一的

2、只有store 可以改变自己的内容

3、Reducer 必须是纯函数 (给定固定的输入,有一定有固定的输出,而且不会有任何的副作用)

3)redux 核心api

1)createStore 创建store

2)store.dispatch 派发action,action 传递给stroe

3)store.getState 获取到所有的store 的数据内容

4)store.subscribe 定义store 改变,只要store 发生改变,store.subscribe 接受的回调函数就会被执行

4) UI 组件和容器组件

1、ui 组件负责渲染(傻瓜组件) ,容易组件处理业务逻辑(聪明组件)

2、无状态组件(就是函数)

优点:性能高 
注:只有render 函数时候,可以无状态组件

5) 异步请求

1)touch *** 创建文件(mac) 安装:npm install --save axios

    componentDidMount(){
        axios.get('/list.json').then((res)=>{
            const data = res.data;
            const action = initListAction(data);
            store.dispatch(action);
        })
    }
  1. Redux-thunk 中间件实现ajax 数据请求

     npm install redux-thunk
     yarn add redux-thunk
    

用了thunk action 可以是个函数 自动化测试比较简单