首先在父级进行注入:
import rootReducer from 'reducers';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(rootReducer,applyMiddleware(thunk))//中间件注入
<Provider store={store}>
{routes}
</Provider>
多个reducer合并到一个:
// reducer/index.js
import { combineReducers } from 'redux'
import * as todoList from './todoList'
const rootReducer = combineReducers({
...todoList,
})
export default rootReducer
reducer文件
//todoList.js
import { handleActions } from 'redux-actions'
//使用了handleActions 方便书写action
const todo = (state, action) => {//中间方法
switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
text: action.text,
completed: false // 刚传入的待办项未完成
}
case 'TOGGLE_TODO':
if (state.id !== action.id) {
return state
}
return Object.assign({}, state, {
completed: !state.completed
})
default:
return state
}
}
const todoListInit = [{//初始化值
id: -3,
text: 'coding',
completed: false,
}, {
id: -2,
text: '打篮球',
completed: false,
}, {
id: -1,
text: 'reading',
completed: true,
}]
export const todoList = handleActions({
'ADD_TODO'(state, action) {
return [
...state,
todo(undefined, action.payload)
]
},
'TOGGLE_TODO'(state, action) {
console.log(action)
return state.map(t => todo(t, action.payload))
},
'DEL_TODO'(state, action) {
return state.filter(t => t.id !== action.payload.id)
},
'AAA_TODO'(state, action) {
console.log(action.val)
return state
},
'CHANGE_TODO'(state,action) {
console.log(action)
return state
}
}, todoListInit)
action文件:
// action/todoList.js
import { createAction } from 'redux-actions'
export const addTodo = createAction('ADD_TODO') //标准的redux创建action
export const setVisibility = createAction('SET_VISIBILITY')
export const toggleTodo = createAction('TOGGLE_TODO')
export const delTodo = createAction('DEL_TODO')
export const changeTodo = createAction('CHANGE_TODO')
export const initFetch = (val) => dispatch => {
dispatch({type: 'AAA_TODO',val:val })
}
组件当中的使用:
import { addTodo,toggleTodo,delTodo,initFetch,changeTodo } from 'actions/todoList' //引入对应方法
submit = (e) => { //redux的直接使用
e.preventDefault()
console.log(this)
if(!this.input.value.trim()){
return
}
this.props.dispatch(addTodo({//标准的redux调用,参数会作为action.payload
id: nextTodoId++,
text: this.input.value,
type: 'ADD_TODO',
}))
this.input.value = ''
}
componentDidMount() {
console.log(this.state.a)
// this.props.dispatch({type:'AAA_TODO'})
this.props.dispatch(initFetch({a:123}))//必须使用中间件thunk才能如此调用;
}
网友评论