store.js
import { applyMiddleware, compose, createStore } from 'redux'
import rootReducer from '../reducers'
const middlewares = []
if (process.env.NODE_ENV === 'development') {
const { logger } = require('redux-logger')
middlewares.push(logger)
}
export const store = compose(applyMiddleware(...middlewares))(createStore)(rootReducer)
reducer index.js
import { combineReducers } from 'redux'
import title from './title'
import friend from './friend'
export default combineReducers({
title,
friend
// friend,
// post
})
friend.js
import { ADD_FRIEND, DEL_FRIEND } from '../actions/friend'
const initialState = {
list: [
{
name: 'ryan', id: 1
},
{
name: 'xiao', id: 2
}
]
}
export default (state = initialState, action = {}) => {
const { type, data } = action
let list = state.list
switch (type) {
case ADD_FRIEND:
list = state.list
list.push(data)
return Object.assign({}, state, { list: [...list] })
case DEL_FRIEND:
list = list.filter(item => item.id !== data)
return Object.assign({}, state, { list: [...list] })
default:
return state
}
}
title.js
import { UPDATE_TITLE } from '../actions/title'
const initialState = '点我!点我!点我!'
export default (state = initialState, action = {}) => {
const { type, data } = action
switch (type) {
case UPDATE_TITLE:
return data
default:
return state
}
}
action friend.js
import { store } from '../store'
export const ADD_FRIEND = 'ADD_FRIEND'
export function addFriend (data) {
const dispatch = store.dispatch
// dispatch({ type: ADD_FRIEND, data })
// request.post("/addFriend",{name}).then(res => {
// dispatch({ type: ADD_FRIEND, data })
// })
setTimeout(() => {
dispatch({ type: ADD_FRIEND, data: { name: 'time-friend', id: 3 } })
}, 200)
}
export const DEL_FRIEND = 'DEL_FRIEND'
export function delFriend (id) {
const dispatch = store.dispatch
dispatch({ type: DEL_FRIEND, data: id })
}
title.js
import { store } from '../store'
export const UPDATE_TITLE = 'UPDATE_TITLE'
export function updateTitle(data) {
const dispatch = store.dispatch
dispatch({ type: UPDATE_TITLE, data })
}