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,失败