logger 中间件
- 安装:yarn add redux-logger
- 导入 redux - logger
- 从 redux 中导入 applyMiddleware 函数
- 将 applyMiddleware() 调用作为 createStotre 函数的第二个参数
- 调用 applyMiddleware 函数时,将 logger 作为参数传入
- 后续调用 store.dispatch( )时,控制台就会出现日志信息输出
store/index.js
import { createStore, applyMiddleware } from 'redux'
import logger from 'redux-logger'
import rootReducer from './reducers'
export default createStore(rootReducer, applyMiddleware(logger))
redux-thunk 使用
redux-thunk 中间件可以处理函数形式的 action , 而在函数形式的 action 以执行异步操作代码,完成异步操作
- 安装:yarn add redux-thunk
- 导入 redux-thunk
- 将 thunk 添加到中间件列表中
- 修改 action creator 返回一个函数
- 在函数形式的 action 中执行异步操作,在异步操作成功后,分发 action 更新状态
store/index.js
import thunk from 'redux-thunk'
import logger from 'redux-logger'
import rootReducer from './reducers'
export default createStore(rootReducer, applyMiddleware(thunk, logger))
store/actions/todo.js
export const clearTodo = () => {
return (dispatch) => {
setTimeout(() => {
dispatch({
type: CLEAR_TODO,
})
}, 1000)
}
}
redux-devtools-extension
步骤
- 保证浏览器安装了 Redux 的开发工具
- 通过包管理器在项目中安装 yarn add redux-extension
- 在store / index.js 中进行配置
- 启动 react 项目中,打开 chrome 开发者工具,测试
- 将 applyMiddleware 套起来
import { createStore, applyMiddleware } from 'redux'
import reducer from './reducers'
import thunk from 'redux-thunk'
import { composeWithDevTools } from 'redux-devtools-extension'
export default createStore(reducer, composeWithDevTools(applyMiddleware(thunk)))