ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Redux笔记合集

2021-12-23 18:05:08  阅读:225  来源: 互联网

标签:const createStore reducer 笔记 state dispatch Redux 合集 store


开头几张图,剩下全靠编
Redux形象图

Redux的在react-redux的架构

代码片段转自Redux 入门教程(一):基本用法--阮一峰的网络日志

Store
import { createStore } from 'redux';
const store = createStore(fn);
State
import { createStore } from 'redux';
const store = createStore(fn);

const state = store.getState();
Action
const action = {
  type: 'ADD_TODO',
  payload: 'Learn Redux'
};
Action Creator
import { createStore } from 'redux';
const store = createStore(fn);
store.dispatch()
import { createStore } from 'redux';
const store = createStore(fn);

store.dispatch({
  type: 'ADD_TODO',
  payload: 'Learn Redux'
});

//结合 Action Creator
store.dispatch(addTodo('Learn Redux'));
Reducer
// 基本形式
const reducer = function (state, action) {
  // ...
  return new_state;
};

// 创建、使用
const defaultState = 0;
const reducer = (state = defaultState, action) => {
  switch (action.type) {
    case 'ADD':
      return state + action.payload;
    default: 
      return state;
  }
};

const state = reducer(1, {
  type: 'ADD',
  payload: 2
});

// store.dispatch方法会触发 Reducer 的自动执行,需要将 Reducer 传入createStore方法
import { createStore } from 'redux';
const store = createStore(reducer);

// 实际调用
const actions = [
  { type: 'ADD', payload: 0 },
  { type: 'ADD', payload: 1 },
  { type: 'ADD', payload: 2 }
];

const total = actions.reduce(reducer, 0); // 3
store.subscribe()
// 对于 React 项目,就是组件的render方法或setState方法)放入listen,就会实现 View 的自动渲染。
import { createStore } from 'redux';
const store = createStore(reducer);

store.subscribe(listener);

// unsubscribe
let unsubscribe = store.subscribe(() =>
  console.log(store.getState())
);

unsubscribe();
Store 实现方式

import { createStore } from 'redux';
let { subscribe, dispatch, getState } = createStore(reducer);

###### Reducer 的拆分合并——combineReducers
```javascript
import { combineReducers } from 'redux';

const chatReducer = combineReducers({
  chatLog,
  statusMessage,
  userName
})

export default todoApp

// 
const reducer = combineReducers({
  a: doSomethingWithA,
  b: processB,
  c: c
})

// 分拆到单个文件
import { combineReducers } from 'redux'
import * as reducers from './reducers'

const reducer = combineReducers(reducers)
主要使用方式
store.dispatch(action);
let nextState = todoApp(previousState, action);
// 设置监听函数
store.subscribe(listener);

//其中
function listerner() {
  let newState = store.getState();
  component.setState(newState);   // 更新component局部的state
}

代码片段转自Redux 入门教程(二):基本用法--阮一峰的网络日志

中间件

在store.dispatch改造:Action

方法: applyMiddlewares[作用是将所有中间件组成一个数组,依次执行], applyMiddleware

同步、异步操作

同步操作只要发出一种 Action 即可,异步操作的差别是它要发出三种 Action。

  • 操作发起时的 Action
  • 操作成功时的 Action
  • 操作失败时的 Action

useReducer

代码片段(用于函数组件),参考用 useReducer 代替 Redux

使用 useReducer 创建状态机
const [state, dispatch] = useReducer(reducer, {
    filter: filterOptions.SHOW_ALL,
    todoList: []
});
使用 createContext 和 useContext 暴露状态机接口
// Context
import {createContext} from 'react';

const Context = createContext(null);

export default Context

// App
function App() {
    const [state, dispatch] = useReducer(reducer, {
        filter: filterOptions.SHOW_ALL,
        todoList: []
    });
    return (
        <Context.Provider value={{ state, dispatch }}>
            <div className="App">
                我是 APP,要点:useReducer 的初始值不要传 null,要初始化,否则使用 ajax fetch 不成功
                <AddTodo/>
                <TodoList/>
                <Filter/>
            </div>
        </Context.Provider>
    );
}

// TodoList Component
const TodoList = () => {
    const {state, dispatch} = useContext(Context);
    useEffect(()=> {
        fetchTodoList(dispatch)
    },[])
    const getVisibleTodoList = (state, filter)=>{
        switch (filter) {
            case filterOptions.SHOW_ALL:
                return state.todoList
            case filterOptions.SHOW_COMPLETE:
                return state.todoList.filter(todo => todo.isComplete)
            case filterOptions.SHOW_UNCOMPLETE:
                return state.todoList.filter(todo => !todo.isComplete)
        }
    }
    return state.todoList.length > 0 ? (
        <ul>
            {getVisibleTodoList(state, state.filter).map((todo, index) => (
                <li key={index} onClick={() => dispatch(toggleTodo(index))}
                    style={{textDecoration: todo.isComplete ? 'line-through' : 'none'}}>{todo.text}</li>
            ))}
        </ul>
    ) : (<div>加载中...</div>);
};

后面的看文章用 useReducer 代替 Redux

标签:const,createStore,reducer,笔记,state,dispatch,Redux,合集,store
来源: https://www.cnblogs.com/huiahh/p/15724249.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有