函数组件中使用redux及中间件logger、thunk

关于在函数组件中去使用redux全局状态管理

一、安装依赖

  • npm i redux -S
  • npm i react-redux -S
  • npm i redux-thunk -S
  • npm i redux-logger -D

二、全局状态 store 的配置

/store/index.js 文件下

import { createStore, applyMiddleware, combineReducers } from 'redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';

import { numReducer } from './reducers/reducer';

const allReducer = combineReducers({
    // 合并所有的 reducer
    numReducer,
})
// 【注意】logger 中间件一般写在最后
// 【作用】打印 store 中前后变化的数据
const store = createStore(allReducer, applyMiddleware(thunk, logger));
export default store;

入口文件 index.js 下

// ...
// index.js 入口页面
import { Provider } from 'react-redux';
import store from './store';
ReactDOM.render(
     <Provider store={store}>
         <App />
     </Provider>
  document.getElementById('root')
);

二、action对象配置、中间件thunk配置

// addAction、reduceAction为同步 action 对象
const addAction = (params?: any) => ({
    type: 'add',
    params
});
const reduceAction = (params?: any) => ({
    type: 'reduce',
    params
});

// action异步执行,实际上就是利用thunk中间件
const asyncAddAction = (params?: any) => {
  return (dispatch) => {
    // 延时器代表(模拟)异步请求
    setTimeout(() => {
      // dispatch 就是通过中间件thunk依赖提供,params是页面调用时传进来的 参数(数据)
	  dispatch(addAction(params));
	},3000)
  }
}
export {
	// 实际上导出异步 action 对象 asyncAddAction 即可;
	// 因为调用asyncAddAction后函数内部异步完成后调用了同步action对象去修改reducer中的数据
    addAction, reduceAction, asyncAddAction
}

三、reducer纯函数配置

const numReducer = (state: any = { num: 0 }, action: any) => {
    switch (action.type) {
        case 'add':
            return { num: state.num + 1 };
        case 'reduce':
            return { num: state.num - 1 };
    }
    return state;
}
export {
    numReducer,
}

四、全局数据store在页面的使用

函数组件模版生成rfc

// ...
// 页面其他内容自行补充
import { useSelector, useDispatch } from 'react-redux';
import { addAction, reduceAction } from './store/actions/action';

const App = (props: any) => {
 	const { num } = useSelector((state: any) => state.numReducer);
    const dispatch = useDispatch();
	return (
	  <div>
		<h2>全局数据store:{num}</h2>
		 <button onClick={() => {
              dispatch(addAction())
         }}>+</button>
         <button onClick={() => {
              dispatch(reduceAction())
         }}>-</button>
         <button onClick={() => {
              dispatch(asyncAddAction())
         }}>异步+</button>
       </div>
	)
}

class类组件用例——rcr生成redux 类组件开发模版

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { addAction, reduceAction } from '../Actions/ActionNumber.js'

export class Demo extends Component {
  constructor(props) {
    super(props);
    this.state = {}; // 页面的state数据
  }

  componentDidmount() {
	// 打印一下props,可以看到引入的全局数据 numReducer 中的数据 num
	console.log(props);
  }
  
  render() {
    return (
      <div>
        <h2>全局数据store:{this.props.num}</h2>
		 <button onClick={() => {
              this.props.addAction()
         }}>+</button>
         <button onClick={() => {
              this.props.reduceAction()
         }}>-</button>
         <button onClick={() => {
              this.props.asyncAddAction()
         }}>异步+</button>
      </div>
    )
  }
}

const mapStateToProps = (state) => ({
  num: state.numReducer.num,
  // ...其他数据,需要那个reducer中的数据就取哪个数据即可
  // 如:count: state.numReducer.count
})

const mapDispatchToProps = {
  // 引入action函数(方法),首先要在最顶部 import 你已经写好的 action 函数
  addAction, reduceAction,asyncAddAction
}

export default connect(mapStateToProps, mapDispatchToProps)(Demo)

五、action中使用中间件thunk

异步action配置好后,页面使用查看第四步

const addAction = (params?: any) => ({
    type: 'add',
    params
});
const reduceAction = (params?: any) => ({
    type: 'reduce',
    params
});
// 中间件的使用
const asyncAddAction = () => {
    return (dispatch) => {
    	// 这里可以做数据请求 list,把dispatch放到.then里面
		dispatch(addAction(list))
	}
}
export {
    asyncAddAction, 
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值