把Action Types单独写入一个文件
写Redux Action的时候,我们写了很多Action的派发,产生了很多Action Types,如果需要action的地方我们就自己命名一个Type,会出现两个问题:
1.这些Types如果不统一管理,不利于大型项目的服用,设置太长会产生冗余代码
2.因为Action 里的Type,一定要和Reducer里的type一一对应,所以这部分的代码或字母写错后,浏览器并没有明确的报错,这给调试带来极大的困难。
那么此篇文章是将Action Types单独拆出一个文件。
actionTypes.js
export const CHANGE_INPUT = 'changeInput';
export const ADD_ITEM = 'addItem';
export const DELETE_ITEM = 'deleteItem';
ToDoList.js
import React, { Component } from 'react';
import 'antd/dist/antd.css'
import {Input,Button,List } from 'antd'
import store from './store/store'
import {DELETE_ITEM,CHANGE_INPUT,ADD_ITEM} from './actionTypes'
// const data=[
// '跑跑卡丁车',
// '穿越火线',
// '真三国无双'
// ]
class ToDoList extends Component {
constructor(props) {
super(props);
this.state = store.getState();
this.storeChange = this.storeChange.bind(this);
store.subscribe(this.storeChange) //订阅Redux的状态
}
render() {
return (
<div>
<Input
placeholder={this.state.inputValue}
style={{width:'250px'}}
onChange={this.inputChangeValue.bind(this)}
/>
<Button type="primary" onClick={this.btnClick.bind(this)}>添加游戏</Button>
<List
bordered
dataSource={this.state.List}
renderItem={(item,index) => (
<List.Item onClick={this.deleteItem.bind(this,index)}>{item}</List.Item>
)}
/>
</div>
)
}
inputChangeValue(e){
const action={
type: CHANGE_INPUT,
value:e.target.value
}
store.dispatch(action)
}
storeChange(){
this.setState(store.getState)
}
btnClick(){
const action={
type:ADD_ITEM
}
store.dispatch(action)
}
deleteItem(index){
const action={
type: DELETE_ITEM,
value:index
}
store.dispatch(action)
}
}
export default ToDoList;
reducer.js
import {DELETE_ITEM,CHANGE_INPUT,ADD_ITEM} from '../actionTypes'
const defaultState = {
inputValue : 'Write Something',
List:[
'跑跑卡丁车',
'穿越火线',
'真三国无双'
]
}
export default (state = defaultState,action)=>{
console.log(state,action)
if(action.type === CHANGE_INPUT){
let newState = JSON.parse(JSON.stringify(state)) //深度拷贝state
newState.inputValue = action.value
return newState
}
if(action.type === ADD_ITEM){
let newState = JSON.parse(JSON.stringify(state))
console.log(newState.inputValue)
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.value,1)
return newState
}
return state
}