redux基本使用

redux flow:
数据放在store里面,store接收一个state和action,根据action的type值通过reducer返回一个新的state,通过action派发react components。

reducer是纯函数 接收旧的state和action 返回新的state

数组reduce

const array1 = [1,2,3,4];
const reducer = (accumulator,currentValue) => accumulator+currentValue;

console.log(array1.reduce(reducer));
console.log(array1.reduce(reducer,5));

函数聚合 按顺序执行f1 f2 f3

function f1(){
    console.log('f1');
    }
    function f2(){
    console.log('f2');
    }
    function f3(){
    console.log('f3');
    }
    function compose(...funcs){
      const len = funcs.length;
      if(len === 0){
        return arg => arg;
      }else if(len === 1){
        return funcs[0];
      }else{
        return funcs.reduce((a,b)=>(...args)=>b(a(...args)));
      }
    }
    compose(f1,f2,f3)();
Redux的使用

是js应用的状态容器。它保证程序行为一致性且易于测试。
page主要做的事情是发布消息和订阅消息
reducer做的事情是接收一个对象,里面有state和action,根本action去处理state,再返回新的state
store做的事情是使用redux的createStore函数,传入reducer,返回store实例
store.subscribe 接受订阅
store.getState 获取state的值
store.dispatch 派发事件

安装:

npm install redux --save

基本使用
src/pages/ReduxPage.js

import React, { Component } from 'react'
import store from '../store/ReduxStore';

export default class ReduxPage extends Component {
    componentDidMount(){
        //订阅
        store.subscribe(()=>{
            this.forceUpdate();
            // this.setState({});
        })
    }
    render() {
        console.log(store);
        return (
            
{/* 获取 */}

{store.getState()}

{/* 发布 */}
) } }

store/counterReducer.js

export function counterReducer(state=0,action){
    switch(action.type){
        case 'add':
            return state + 1;
        case 'minus':
            return state - 1;
        default:
            return state;
    }
}
 

store/ReduxStore.js

import {createStore} from 'redux';
import {counterReducer} from './counterReducer';

const store = createStore(counterReducer);

export default store;

你可能感兴趣的:(redux基本使用)