2020-11-10

import { Switch } from 'antd';
import { Component } from 'react';
import { createStore } from 'redux'
//生成store  fn函数
//store保存数据的地方
const store = createStore(fn)
//state 对象包含所有数据,某时刻的数据生成快照就是State
const state = store.getState();
//action是一个对象,必须包含type属性表示action名称
const action ={
    // 名称ADD——TODO
    type:'ADD_TODO',
    //携带的信息
    payload:'Learn Redux'
}
//view发送多少种消息就会有多少种action,定义一个函数生成action/ Action Creat
const ADD_TODO ='添加 TODO'
function Action Creat(text){
    return{
        type:ADD_TODO,
        text
    }
}
const action = addTodo('Learn Redux')

//store.dispatch()是view发出action的唯一方法
import { createStore} from 'redux'
const store = createStore(fn)
store.dispath({
    type:'ADD_TODO',//接受一个action对象作为参数将他送出去
    payload:'Learn Redux'
})
//结合Action Creator
store.dispath(addToDo('Learn Redux'))
//Reducer在store里,接受state返回新的state
const reducer = function (state,action){
    //...
    return new_state
}
//将整个应用的初始状态作为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时将reducer传入createStore方法
const store = createStore(reducer)
//reducer拆分
const chatReducer = (state = defaultState,action={})=>{
    return{
        chatLog:chatLog(state.chatLog,action),
        statusMessage:statusMessage(state.statusMessage,action),
        userName:userName(state.userName,action)
    }
}
//redux提供combineReducers方法用于reducer拆分,只需要定义子reducer函数,用conbineReducers把他们合成大的reducer
import { combineReducers } from 'redux'
//state属性与子Reducer同名
const chatReducer = combineReducers({
    chatLog,
    statusMessage,
    userName
})
export default todoApp

//流程

//1,首先用户发出action
store.dispath(action)
//2,store调用reducer函数并传入两个参数:(1)当前state(2)action\
let nextState = todoApp(previousState,action)
//state一旦有变化store调用监听函数
store.subscribe(listener)
//listener可以通过store.getState()得到当前状态
function listener(){
    let newState = store.getState();
    Component.setState(newState)
}


//redux-saga是一个库,以redux中间件的形式而存在管理side effect

//为了处理异步操作引入中间件middleware

//日志中间件 redux-logger

import { applyMiddleware,createStore } from 'redux'

import createLogger from 'redux-loggger'

const logger = createLogger();

const store = createStore(

reducer,

applyMiddleware(logger)//有几个参数就有几个中间件,次序有要求

)

//异步操作基本思路

//三个action

//1,发起 2,成功 3,失败

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值