新建actionType文件

将组件中的action type 写入其中并向外暴露
image.png

  1. export const CHANGE_INPUT='changeInput'
  2. export const ADD_ITEM='addItem'
  3. export const DELETE_ITEM='deleteItem'

新建actionCreators文件

将**actionType**引入,并向外暴露各自的action方法

  1. import {CHANGE_INPUT,ADD_ITEM,DELETE_ITEM} from './actionTypes'
  2. export const changeInputAction =(value)=>({
  3. type:CHANGE_INPUT,
  4. value
  5. })
  6. export const addItemAction =()=>({
  7. type:ADD_ITEM,
  8. })
  9. export const deleteItemAction =(index)=>({
  10. type:DELETE_ITEM,
  11. index
  12. })

reducer文件中引入actionType文件

  1. import {CHANGE_INPUT,ADD_ITEM,DELETE_ITEM} from './actionTypes'
  2. const defaultState = {
  3. inputValue: "",
  4. list: ["8:00,开会", "9:00,二开", "10:00,散开"],
  5. };
  6. export default (state = defaultState, action) => {
  7. console.log(state, action);
  8. //Reducer里只能接收 state 不能改变state
  9. if (action.type === CHANGE_INPUT) {
  10. let newState = JSON.parse(JSON.stringify(state));
  11. newState.inputValue = action.value;
  12. return newState;
  13. }
  14. if (action.type === ADD_ITEM) {
  15. let newState = JSON.parse(JSON.stringify(state));
  16. newState.list.push(newState.inputValue);
  17. newState.inputValue = "";
  18. return newState;
  19. }
  20. if (action.type === DELETE_ITEM) {
  21. let newState = JSON.parse(JSON.stringify(state));
  22. newState.list.splice(action.index,1)
  23. return newState;
  24. }
  25. return state;
  26. };

组件中引入actionCreators和其中的方法

修改原来的action变量为新的action方法

  1. import {changeInputAction,addItemAction,deleteItemAction} from './store/actionCreators';
  2. changeInputValue = (e) => {
  3. console.log(e.target.value);
  4. const action = changeInputAction(e.target.value)
  5. store.dispatch(action);
  6. };
  7. clickBtn = () => {
  8. const action = addItemAction()
  9. store.dispatch(action);
  10. };
  11. deleteItem=(index)=>{
  12. const action = deleteItemAction(index)
  13. store.dispatch(action);
  14. }

优点:减少代码冗余,书写错误会有报错