actionType
export const ADD_ITEM = 'addItem'
export const REMOVE_ITEM = 'removeItem'
actionCreator
import { ADD_ITEM, REMOVE_ITEM } from './actionTypes'
export const addUserItem = (data) => {
return {
type: ADD_ITEM,
data
}
}
export const removeUserItem = (index) => {
return {
type: REMOVE_ITEM,
index
}
}
reducer
import { ADD_ITEM, REMOVE_ITEM } from '../action/actionTypes'
const initState = [
{
name: '张三',
age: 18
},
{
name: '李四',
age: 20
},
{
name: '王五',
age: 21
},
]
export default (state = initState, action) => {
switch (action.type) {
case ADD_ITEM:
return [
...initState,
action.data
]
case REMOVE_ITEM:
const newList = JSON.parse(JSON.stringify(initState))
newList.splice(action.index)
return newList
default:
return state
}
}
store
import {createStore} from 'redux'
import allReducers from './reducer'
const store = createStore(allReducers)
export default store
App.jsx
import React from 'react';
import store from './store'
import {addUserItem, removeUserItem} from './store/action/actiosCreator'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
list: store.getState()
}
store.subscribe(() => {
this.setState(() => {
return {
list: store.getState()
}
})
})
this.handleAddItem = this.handleAddItem.bind(this)
this.handleRemoveItem = this.handleRemoveItem.bind(this)
}
handleRemoveItem(index, e) {
store.dispatch(removeUserItem(index))
}
handleAddItem() {
store.dispatch(addUserItem({name: '赵六', age: 50}))
}
render() {
return (
<div>
<ul>
{this.state.list.map((item, index) => (
<li style={{background: 'pink', marginTop: '10px'}} key={index} onClick={(e) => {this.handleRemoveItem(index, e)}}>
<span>{item.name}</span> ----------- <span>{item.age}</span>
</li>
))}
<button onClick={this.handleAddItem}>添加</button>
</ul>
</div>
)
}
}
export default App;