欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

redux

程序员文章站 2022-07-16 14:27:08
...

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 [email protected]>=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())
    ));
  }

上一篇: 项目action封装

下一篇: Redux知识点