首先先安装redux cnpm i redux --save,然后开始构建redux
actionTypes.js,此文件用于使用常量的方式存储action的type类型
export const CHANGE_INPUT_VALUE = 'change_input_value'
export const ADD_TODO_ITEM = 'add_todo_item'
export const DELETE_TODO_ITEM = 'delete_todo_item'
export const INIT_LIST_ACTION = 'init_list_action'
export const GET_INIT_LIST = 'get_init_list'
actionCreators.js,此文件用于封装action,简化在TodoList中的组件代码
import {
CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM,
INIT_LIST_ACTION, GET_INIT_LIST} from './actionTypes'
export const getInputChangeAction = (value) => {
return {
type: CHANGE_INPUT_VALUE,
value
}
}
export const getAddItemAction = () => {
return {
type: ADD_TODO_ITEM
}
}
export const getDeleteItemAction = (index) => {
return {
type: DELETE_TODO_ITEM,
index
}
}
export const initListAction = (data) => {
return {
type: INIT_LIST_ACTION,
data
}
}
index.js
import {
createStore} from 'redux'
import reducer from './reducer'
const store = createStore(reducer)
export default store
reducer.js
import {
CHANGE_INPUT_VALUE, ADD_TODO_ITEM, DELETE_TODO_ITEM, INIT_LIST_ACTION, } from './actionTypes'
const defaultState = {
inputValue: '',
list: []
}
export default (state = defaultState, action) => {
if (action.type === CHANGE_INPUT_VALUE) {
const newState = JSON.parse(JSON.stringify(state))
newState.inputValue = action.value
return newState
}
if (action.type === ADD_TODO_ITEM) {
const newState = JSON.parse(