首先全局狀態(tài)有幾部分組成
1杏瞻、store--全局狀態(tài)容器,整個(gè)應(yīng)用的數(shù)據(jù)存儲中心
2、action--view 層與data層的過渡
3衙荐、reducer--接收action并更新Store捞挥,所有的函數(shù)處理處理都在reducer里面執(zhí)行,reducer返回新的state忧吟,更新界面
一個(gè)redux的更新流程就是這樣的砌函,說的不對請大家指正!!
按照上面的流程來配置項(xiàng)目
1讹俊、首先下載插件
yarn add redux react-redux
2垦沉、項(xiàng)目下面創(chuàng)建store文件夾里面分別新建 index.js、action.js仍劈、actionType.js厕倍、reducer.js
index.js代碼
/*combineReducers 合并多個(gè)store,便于管理
*applyMiddleware
*createStore創(chuàng)建store
*/
import {createStore,combineReducers,applyMiddleware} from 'redux'
import immutable from 'redux-immutable-state-invariant'
//安裝redux-devtools-extension的可視化工具
import { composeWithDevTools } from 'redux-devtools-extension'
//引入異步中間件
import thunkMiddleware from 'redux-thunk'
import index from './reducer';
const reducer = combineReducers({
home:index
})
const middlewares = [thunkMiddleware];
if (process.env.NODE_ENV !== 'production') {
middlewares.push(immutable())
}
const storeEnhancers = process.env.NODE_ENV !== 'production' ?
composeWithDevTools(
applyMiddleware(...middlewares),
) :
applyMiddleware(...middlewares);
const store = createStore(reducer,{},storeEnhancers)
export default store;
actionType.js
export const SAVEUSERINFO = 'SAVEUSERINFO';
action.js
import {SAVEUSERINFO} from './actionTypes'
export const saveUserInfo = (value) => ({
type: SAVEUSERINFO,
value: value
});
reducer.js
const defaultState = {
userInfo: {token: ''}
}
//reducer 可以接受state但是不可以修改state 只有store才能改變
//純函數(shù)指得是贩疙,制定固定的輸入讹弯,就一定會有固定的輸出,而且不會有任何副作用
export default (state = defaultState, action) => {
switch (action.type) {
case "SAVEUSERINFO":
return {
...state,userInfo:action.value
}
default:
break
}
return state
}