浅谈redux、applyMiddleware、redux-thunk

redux是一个可预测的状态管理工具,唯一可以改变state的方式就是dispatch一个action,action描述了以何种方式改变state,交由reducer去改变state。

创建redux应用

npm i redux

src/index.js:

import {
   createStore} from 'redux'

const initState = {
   
    list: []
}

//  reducer,createStore的第一个参数,当store初始化的时候redux会调用reducer,传入state为undefined,action.type为一个@@redux/INIT开头的随机字符串
//  所以在这里可以设置state的默认值,防止下次reducer改变数据的时候报错
//  reducer应当返回一个state,来作为新的state。
function todo(state = initState, action){
   
    switch(action.type){
   
        case 'todoAdd':
            return {
   
                list: state.list.concat(action.text)
            }
        case 'todoRemove':
            return {
   
                list: state.list.filter((v) => v !== action.text)
            }
        default: 
            return state
    }
}

let store = createStore(todo)

//订阅store更新
store.subscribe(() => {
   
    console.log(store.getState())
})

//派发action,这个action会被传入到reducer的第二个参数
store.dispatch({
   
    type: 'todoAdd',
    text: '吃饭',
})
store.dispatch({
   
    type: 'todoAdd',
    text: '睡觉',
})
store.dispatch({
   
    type: 'todoAdd',
    text: '打豆豆',
})
store.dispatch({
   
    type: 'todoRemove',
    text: '睡觉',
})

控制台打印结果为:
打印结果

合并reducer

假如说有多个reducer,一个是todo,另外一个是用户数据,我们可以使用redux提供的combineReducers来合并reducer,src下新建一个文件夹为store,src/store/index.js为创建的store,src/store/todo.js和src/store/user.js分别为todo的reducer和user的reducer。
src/store/index.js代码为:

import {
   createStore, combineReducers} from 'redux'
import todo from './todo'
import user from './user'

const reducer = combineReducers({
   
    todo,
    user,
})

const store = createStore(reducer)

export default store

src/store/user.js代码为

const initState = {
   
    name: 'xiaobai',
    age: 18,
}

function user(state = initState, action){
   
    switch(action.type){
   
        case 'userAgeAdd':
            return {
   
                ...state,
                age: state.age + 1,
            }
        case 'userNameChange':
            return {
   
                ...state,
                name: action.name,
            }
        default: 
            return state
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值