Redux

使用 redux
首先要创建一个 store
而createStore 需要传入一个 reducer

import { createStore, combineReducers, bindActionCreators} from "redux"

// store inital state
const initialState = {count :0}
 
// reucer
const counter = (state = initialState,action) =>{
    switch (action.type){
        case "PLUS_ONE":
            return { count:state.count +1 };
        case "CUSTOM_COUNT":
            return {
                count:state.count + action.payload.count
            }
        default:
                break;
    }
    return state
}

// 第二个 reducer
const todos = (state={})=> state

// Create store
//const store = creactStore(counter)
const store = createStore(combineReducers({//有多个 reducer 时,生成 store 要借用 combineReducers 方法
    todos,
    conuter,    
}))

// Action creator
function plusOne(){
    // action
    return {type: "PLUS_ONE"} 
}
function customCount(count){
    return { type:"CUNSTOM_COUNT",payload:{count} };
}



store.subscribe( () => console.log(store.getState()));

//store.dispatch(plusOne()); //使 state +1
plusOne = bindActionCreators(plusOne,store.disptch); //使用  bindActionCreators 包装后,可以用下面的语句实现上面一行语句的效果,使代码简洁
plusOne();

store.dispatch(customCount(5)); // 使得 state +5
Comments
Write a Comment