1. 程式人生 > >immutable.js案例

immutable.js案例

header元件的store/actionCreators.js

import * as actionTypes from './actionTypes'
import axios from 'axios'
import { fromJS }from 'immutable'
export const getFocusAction=()=>{
return{
type:actionTypes.SEARCH_FOCUS,
}
}
export const getBlurAction=()=>{
return{
type:actionTypes.SEARCH_BLUR,
}
};
export const changeList=(data)=>{
return {
type:actionTypes.CHANGE_LIST,

//將要傳給reducer的資料也變為immutable型別的資料
data:fromJS(data)
}
};
由於在主的store/index.js中使用了redux-thunk,所以才可以在
actionCreators.js中返回一個函式呼叫api
export const getList = () =>{
return (dispatch) => {
axios.get('/api/headerList.json')
.then((res)=>{
let data0=res.data;
console.log("res.data:",res.data);
dispatch(changeList(data0.data));
})
.catch((error)=>{
console.log('error')
})
}
}

header元件下的store/reducer.js

import * as contants from './actionTypes';
import { fromJS } from 'immutable';

當外層用了fromJS後,內部的list也會變為immutable物件
const defaultState=fromJS({
    focused:false,
    list:[]
});

export default(state=defaultState,action)=>{
    if(action.type===contants.SEARCH_FOCUS){
        return state.set('focused',true);
    }
    if(action.type===contants.SEARCH_BLUR){
        return state.set('focused',false);
    }
    if(action.type===contants.CHANGE_LIST){
        console.log("action.data:",action.data);
    所有在接收到action裡面的list資料時,要確保此時接受的資料也要是immutable物件


       return state.set('list',action.data);
    }
    return state
}