store是一个状态管理容器,它通过createStore创建,createStore接收initialState和reducer两个参数。它暴露了4个api分别是:
getState()
dispatch(action)
subscribe(listener)
replaceReducer
前三个是比较常用的api,之后我们会来模拟实现一个createStore这个函数。
在redux思想中view的变化由action发出通知,action是一个包含type的简单对象,在redux思想中改变state的唯一方法就是触发action
dispatch用来处理action,并传递给reducer,继而更新应用状态
Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
在React中使用redux的数据流向如图所示:
结构如下
store.js
import { createStore } from 'redux'
import { rootReducer } from './reducer/index';const store = createStore(rootReducer)export default store;
action/index.js
/*** action 构建函数*/
export const sendAction = (obj) => {// console.log(obj);// 需要返回一个action对象,该action对象需要包括type等属性return {type: 'send-action',value: '这是一个action'}
}
redecer/index.js
/*** 该文件是创建reducer函数,专门用于处理发送过来的action*/const initState = {value: '默认值'
}
// 函数需要传递两个参数:state,action
const rootReducer = (state = initState, action) => {// 根据aciton中的type字段判断是否为发送过来的action,如果是则返回一个新的stateswitch (action.type) {case 'send-action':return Object.assign({}, state, action)default:return state}
}
export {rootReducer
};
项目中使用
…未完待续