新建actionType文件
将组件中的action type 写入其中并向外暴露
export const CHANGE_INPUT='changeInput'
export const ADD_ITEM='addItem'
export const DELETE_ITEM='deleteItem'
新建actionCreators文件
将**actionType**引入,并向外暴露各自的action方法
import {CHANGE_INPUT,ADD_ITEM,DELETE_ITEM} from './actionTypes'
export const changeInputAction =(value)=>({
type:CHANGE_INPUT,
value
})
export const addItemAction =()=>({
type:ADD_ITEM,
})
export const deleteItemAction =(index)=>({
type:DELETE_ITEM,
index
})
reducer文件中引入actionType文件
import {CHANGE_INPUT,ADD_ITEM,DELETE_ITEM} from './actionTypes'
const defaultState = {
inputValue: "",
list: ["8:00,开会", "9:00,二开", "10:00,散开"],
};
export default (state = defaultState, action) => {
console.log(state, action);
//Reducer里只能接收 state 不能改变state
if (action.type === CHANGE_INPUT) {
let newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
return newState;
}
if (action.type === ADD_ITEM) {
let newState = JSON.parse(JSON.stringify(state));
newState.list.push(newState.inputValue);
newState.inputValue = "";
return newState;
}
if (action.type === DELETE_ITEM) {
let newState = JSON.parse(JSON.stringify(state));
newState.list.splice(action.index,1)
return newState;
}
return state;
};
组件中引入actionCreators和其中的方法
修改原来的action变量为新的action方法
import {changeInputAction,addItemAction,deleteItemAction} from './store/actionCreators';
changeInputValue = (e) => {
console.log(e.target.value);
const action = changeInputAction(e.target.value)
store.dispatch(action);
};
clickBtn = () => {
const action = addItemAction()
store.dispatch(action);
};
deleteItem=(index)=>{
const action = deleteItemAction(index)
store.dispatch(action);
}