上一篇介绍
redux包含三个主要内容store,action,reducer,这一节对这三个进行进一步理解
store可以理解为接口,是组件与数据交互的接口,store.getState()获取数据;store.dispatch(action) 提交action,创建store时使用createStore(reducer)将reducer封装进入store内
action翻译过来是行动,动作的意思,其实它本身意思也是如此,是页面发生动作以后,将变化的数据提交给store,每个action必须是唯一的,因此action对象里有一个属性type,是action的唯一性标识
reducer 可以理解为数据处理,返回新的state状态数据,因为我们每次获取action后需要深copy一个新的state,处理后返回这个state
store下分配了4个文件,分别存放index,reducer,action的type,action对象:如下所示
index中创建store
创建store
import {createStore,applyMiddleware} from 'redux'
import reducer from './reducer.jsx'
import thunk from 'redux-thunk'
const store = createStore(reducer,applyMiddleware(thunk))
export default store
reducer
导出newstate
import {INPUT_VALUE,ADD_VALUE,DELETE_VALUE,DATA_LIST} from './actionType.jsx'
const defaultState = {
value:"",
datalist:[1,2,3,4,5]
}
export default (state=defaultState,action)=>{
if(action.type===INPUT_VALUE){
let newstate = JSON.parse(JSON.stringify(state))
newstate.value = action.value
return newstate
}
if(action.type===ADD_VALUE){
let newstate = JSON.parse(JSON.stringify(state))
newstate.datalist.push(action.value)
return newstate
}
if(action.type===DELETE_VALUE){
let newstate = JSON.parse(JSON.stringify(state))
newstate.datalist.splice(action.index,1)
return newstate
}
if(action.type===DATA_LIST){
let newstate = JSON.parse(JSON.stringify(state))
newstate.datalist = action.datalist
return newstate
}
return state
}
actionType
导出action.type
export const INPUT_VALUE = 'inputvale'
export const ADD_VALUE = 'addvalue'
export const DELETE_VALUE = 'deletevalue'
export const DATA_LIST = "data_list"
actionCreator
导出action对象
import {INPUT_VALUE,ADD_VALUE,DELETE_VALUE,DATA_LIST} from './actionType.jsx'
export const actionChangeInput = (data)=>({
type:INPUT_VALUE,
value:data
})
export const actionAddList = (data)=>({
type:ADD_VALUE,
value:data
})
export const actionDeleteList = (index)=>({
type:DELETE_VALUE,
index:index
})
export const actionGetDatalist = ()=>{
const datalist = [2,3,4,5,6]
return (dispatch)=>{
let action = {
type:DATA_LIST,
datalist:datalist
}
dispatch(action)
}
}
redux-thunk是redux的中间件,作用:可以从外部引入方法,这个方法最终返回的依然是一个action,因此在展示页面中必须使用store.dispatch(action)提交action
这东西就只需要导入就可以使用了
导入方式见上面index文件,