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类型的数据,
actionCreators.js中返回一个函数调用api
data:fromJS(data)
}
};
由于在主的store/index.js中使用了redux-thunk,所以才可以在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
}