HOOKS使用redux及部分方法

创建redux基本步骤

1.新建action-type.js文件(操作类型)
在这里插入图片描述基本结构如下:

export const xxx =  'xxxx'

2.新建reducer.js文件
在这里插入图片描述
主要是结构:

const xxxx =  (state,action) => {
switch (action.type) {
	case xxx: 
		//操作
		break
	}
}
  1. 创建store ,多个reduce人可以合并使用
    在这里插入图片描述
    基本用法:
    combineReducers:用于合并多个reducer
    例如:需要明确键值对
	const reducer = combineReducers(
		{ count:count,
		  other:other
		})
	 createStore:创建store;
	 例如:
	const store= createStore(reducer)

在页面上引用store

主要分为页面单独引用全局引用,下面将一一介绍两种情况的用法和注意事项;

  • 注意事项:使用subscribe 监听store变化;使用store.getState90获取数据
  • 页面引用(直接在页面上引入store)
    在这里插入图片描述
    获取后的count,直接在页面上渲染使用,也可以直接dispatch更改count的值
    在这里插入图片描述

全局引用store

注意事项:

  1. hooks中使用useSelector()获取store的值;
  2. 使用useDispatch获取dispatch
  3. 使用provider组件包括全局;
app.js || xxx.js
import { Provider } from 'react-redux'
import store from "../../store/index";
  function () {
  returrn {
   <Provider store={store}> // 往下级组件传store
	</ xxxxxx>
   </Provider>
  }
}

子组件:

child.js || xxx.js
app.js || xxx.js
import {useSelector,useDispatch} from 'react-redux'   
function (props) {
 const count = useSelector(state => state.count); // 接收store的值
 const other = useSelector(state => state.other);
 const dispatch = useDispatch(); // 接收dispatch
 returrn {
  <>
    <div onClick={() => dispatch({type:'ADD'})}>text页面</div>
    <div onClick={() => dispatch({type:'NEW',text:'88888'})}>other页面</div>
  </>
 }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值