redux-logger
redux-logger
用于处理日志记录的中间件。redux-logger
中间件就是⼀个函数,对store.dispatch
⽅法进⾏改造,在发出Action
和执⾏Reducer
这两步之间,添加了其他功能。
使用
-
安装
redux
yarn add redux
-
store --> index.js
用于创建Store
import { createStore, combineReducers,applyMiddleware } from "redux";
import { countReducer, usernameReducer } from "./reducer";
import Thunk from 'redux-thunk';
import Logger from 'redux-logger';
const reducer = combineReducers({
count:countReducer,
username:usernameReducer
});
const store = createStore(reducer,applyMiddleware(Logger,Thunk))
export default store; -
store --> reducer.js
用于统一维护Reducer
export const countReducer = (state=0,action)=>{
switch(action.type){
case "add":
return state+action.data;
case "min":
return state-action.data;
default:
return state;
}
}
export const usernameReducer = (state='柏拉文',action)=>{
switch(action.type){
case "change":
return action.data;
default:
return state;
}
} -
indes.js
入口文件全局订阅Store
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import store from './store'
const render = () => {
ReactDOM.render(
<App />,
document.getElementById('root')
);
}
render();
// 订阅 store
store.subscribe(render); -
app.js
app组件使用Store
以及派发Store
import store from './store'
function App() {
const state = store.getState();
console.log(state);
const handleChangeUsername = (value) => {
// store 派发 修改 username Reducer
store.dispatch({ type: 'change', data: value });
}
const handleChangeUsernameAsync = (value) => {
// store 派发 修改 username Reducer
store.dispatch((dispatch) => {
setTimeout(() => {
dispatch({ type: 'change', data: value });
}, 300);
});
}
const handleAddCount = (value) => {
// store 派发---同步增加 count Reducer
store.dispatch({ type: 'add', data: value });
}
const handleMinCount = (value) => {
// store 派发---同步减少 count Reducer
store.dispatch({ type: 'min', data: value });
}
const handleAddCountAsync = (value) => {
// store 派发---异步增加 count Red ucer
store.dispatch((dispatch) => {
setTimeout(() => {
dispatch({ type: 'add', data: value });
}, 300);
});
}
const handleMinCountAsync = (value) => {
// store 派发---异步减少 count Reducer
store.dispatch((dispatch) => {
setTimeout(() => {
dispatch({ type: 'min', data: value });
}, 300);
});
}
return (
<div className="App">
<h3>{state.username}</h3>
<h3>{state.count}</h3>
<div>
<button onClick={() => handleChangeUsername('柏拉文修改')}>同步修改 username</button>
<button onClick={() => handleChangeUsernameAsync('柏拉文修改')}>异步修改 username</button>
<button onClick={() => handleAddCount(1)}>同步增加 count</button>
<button onClick={() => handleMinCount(1)}>同步减少 count</button>
<button onClick={() => handleAddCountAsync(1)}>异步增加 count</button>
<button onClick={() => handleMinCountAsync(1)}>异步减少 count</button>
</div>
</div>
);
}
export default App;