redux

作者: Biao_349d | 来源:发表于2018-09-28 18:33 被阅读0次

    redux学习笔记

    基本概念

    1. Action
      Action 是定义一个切换获取数据的方式。
      简单解释: 我有一个柜子, 柜子上面有十个盒子, 但是这时候, 你不知道改打开那个盒子, 这时候, 切换active.type就可以帮你找到对应的盒子。
    {
        type: 'hezi01',
        text: '盒子01'
    }
    
    {
        type: 'hezi02',
        text: '盒子02'
    }
    
    {
        type: 'hezi03',
        text: '盒子03'
    }
    
    。。。
    
    1. Action 创建函数
    • 在 Redux 中的 action 创建函数只是简单的返回一个 action:
    function addTodo(text) {
      return {
        type: ADD_TODO,
        text
      }
    }
    
    1. store.dispatch()
    • 往store添加一个action, 并切换到当前这个type
    store.dispatch(addTodo('Learn Redux'));
    
    • 切换到当前action.type
          store.dispatch({type: "DECREMENT"})
    
    1. reducer
    • 初始化数据, 并初始化切换数据条件
    export default (state = 0, action) => {
        switch (action.type) {
            case 'INCREMENT':
                return state + 1
            case 'DECREMENT':
                return state - 1
            default:
                return state
        }
    }
    
    1. 合并reducer
    • 如果有更多reducer, combineReducers能合并reducer;
    import { combineReducers } from 'redux'
    
    const todoApp = combineReducers({
      visibilityFilter,
      todos
    })
    
    
    • 引入reducer
      你可以把所有子 Reducer 放在一个文件里面,然后统一引入
    import { combineReducers } from 'redux'
    import * as reducers from './reducers'
    
    const reducer = combineReducers(reducers)
    

    6 . store

    • subscribe 监听函数
    // 设置监听函数
    store.subscribe(listener);
    
    1. 中间件
    import { applyMiddleware, createStore } from 'redux';
    import createLogger from 'redux-logger';
    const logger = createLogger();
    
    const store = createStore(
      reducer,
      [initial_state,]  //初始化store
      applyMiddleware(logger)
    );
    
    1. applyMiddleware

    它是 Redux 的原生方法,作用是将所有中间件组成一个数组,依次执行

     applyMiddleware(thunk, promise, logger)
    
    1. 异步操作
    export const fetchFiends() = ()=> {
        return dispatch => {
            dispatch({type: 'FETCH_FRIENDS'})
            return fetch('http://localhost/api.firend')
            .then(res => res.json())
            .then(json => {
                dispatch({type: 'RECEIVE_FRIEDS', payload: json})
            })
        }
     }
    
    1. redux-thunk中间件 让dispatch接收函数
    
    import { createStore, applyMiddleware } from 'redux';
    import thunk from 'redux-thunk';
    import reducer from './reducers';
    
    // Note: this API requires redux@>=3.1.0
    const store = createStore(
      reducer,
      applyMiddleware(thunk)
    );
    
    const fetchPosts = postTitle => (dispatch, getState) => {
      dispatch(requestPosts(postTitle));
      return fetch(`/some/API/${postTitle}.json`)
        .then(response => response.json())
        .then(json => dispatch(receivePosts(postTitle, json)));
      };
    };
    
    // 使用方法一
    store.dispatch(fetchPosts('reactjs'));
    // 使用方法二
    
    1. redux-promise 中间件 让dispatch接收promise
    
    import { createStore, applyMiddleware } from 'redux';
    import promiseMiddleware from 'redux-promise';
    import reducer from './reducers';
    
    const store = createStore(
      reducer,
      applyMiddleware(promiseMiddleware)
    );
    
    
    
    • 写法一
    const fetchPosts =
      (dispatch, postTitle) => new Promise(function (resolve, reject) {
         dispatch(requestPosts(postTitle));
         return fetch(`/some/API/${postTitle}.json`)
           .then(response => {
             type: 'FETCH_POSTS',
             payload: response.json()
           });
    })
    
    • 写法二
    • createAction第二个参数接收promise对象
    import { createAction } from 'redux-actions';
    
    class AsyncApp extends Component {
      componentDidMount() {
        const { dispatch, selectedPost } = this.props
        // 发出同步 Action
        dispatch(requestPosts(selectedPost));
        // 发出异步 Action
        dispatch(createAction(
          'FETCH_POSTS',
          fetch(`/some/API/${postTitle}.json`)
            .then(response => response.json())
        ));
      }
    

    相关文章

      网友评论

          本文标题:redux

          本文链接:https://www.haomeiwen.com/subject/dhapoftx.html