需要改一改 之前这样的写法

1. 在 src/store 文件夹下新建 actionTypes.js 文件

actionTypes.js 文件 , 把字符串提取出来,可以避免写错
export const CHANGE_INPUT_VALUE = 'change_input_value';
export const ADD_TODO_ITEM = 'add_todo_item';
export const DELETE_TODO_ITEM = 'delete_todo_item';
2. 在 TodoList.js 中 引入 actionTypes.js 文件
import { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM } from './store/actionTypes'
//把 action 的 type 替换一下
handleInputChange(e) {
// 1.创建action方法
const action = {
type: CHANGE_INPUT_VALUE,
value: e.target.value
}
//2.调用store 的 dispatch把 action 派发给store
//Store 接收到 action 会自动帮我们把 之前的数据(previousState)和 action 传递给 Reducer
store.dispatch(action)
console.log(e.target.value);
}
handleStoreChange() {
this.setState(store.getState())
}
handleBtnClick() {
const action = {
type: ADD_TODO_ITEM
}
store.dispatch(action)
}
handleItemDelete(index) {
const action = {
type: DELETE_TODO_ITEM,
index
}
store.dispatch(action)
console.log(index);
}
3.把 reducer.js 里 action 的 type 也替换一下
import { CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM } from './actionTypes'
// 存放公用的数据
const defaultDate = {
inputValue: '',
list: ['1', '2', '3', '4', '5']
}
// reducer 返回的必须是一个函数,这个函数接收两个参数(state 和 action)
// state = defaultDate 表示 Store 上一次 存储的数据,action 表示用户传过来的话
// reducer 可以接收state,但是不能修改state
export default (state = defaultDate, action) => {
console.log(state, action);
if (action.type === CHANGE_INPUT_VALUE) {
const newState = JSON.parse(JSON.stringify(state))
// 把inputValue改成最新的value
newState.inputValue = action.value
return newState
}
if (action.type === ADD_TODO_ITEM) {
const newState = JSON.parse(JSON.stringify(state))
// newState.inputValue 上一次action type中 change_input_value改变的Value
newState.list.push(newState.inputValue)
newState.inputValue = ''
return newState
}
if (action.type === DELETE_TODO_ITEM) {
const newState = JSON.parse(JSON.stringify(state))
newState.list.splice(action.index, 1)
return newState
}
return state
// 返回 state
}
网友评论