React-Redux => ImmutableJS
store
——reducer.js
import * as constants from './constants';
import { fromJS } from 'immutable';
const defaultState = fromJS({
list: [],
inputValue: ''
})
export default (state = defaultState, action) => {
if (action.type === constants.INIT_TODO_LIST) {
return state.set('list', action.value)
}
if (action.type === constants.CHANGE_INPUT_VALUE) {
return state.set('inputValue', action.value)
}
if (action.type === constants.ADD_TODO_ITEM) {
return state.merge({
list: state.get('list').concat(state.get('inputValue')),
inputValue: ''
})
}
if (action.type === constants.DELETE_TODO_ITEM) {
return state.set('list', state.get('list').splice(action.value, 1))
}
return state
}
store
——actionCreators.js
import * as constants from './constants'
import axios from 'axios'
import { fromJS } from 'immutable';
export const getInputChangedAction = (value) => ({
type: constants.CHANGE_INPUT_VALUE,
value: fromJS(value)
})
export const getTodoAddedAction = () => ({
type: constants.ADD_TODO_ITEM
})
export const getTodoDeletedAction = (value) => ({
type: constants.DELETE_TODO_ITEM,
value: fromJS(value)
})
export const initTodoListAction = (value) => ({
type: constants.INIT_TODO_LIST,
value: fromJS(value)
})
export const getTodoList = () => {
return (dispatch) => {
axios.get('/api/todo.json').then((res) => {
const result = res.data.data;
dispatch(initTodoListAction(result.list))
})
}
}
TodoList.js
const mapStateToProps = (state) => {
return {
list: state.get('list'),
inputValue: state.get('inputValue')
}
}
网友评论