ReactHook ReducerHook

触发dispatch方法后会刷新函数组件

1、创建action-type.js文件
	
	用途:
		用来放置action的type属性的常量
	
	export const XX='XX'

2、创建actions.js
		
	(1)引入action-type.js
		import { xx,xx,.. } from "./action-type";
		
	(2)通过函数返回action对象
		export const xx=(数据参数)=>({type:XX,data:参数}); 
			其中:除了type属性外其他可自定义

3、创建reducers.js文件
	管理状态数据,每一个返回值就是存储的数据
	
	(1)引入action-type.js
	import { xx,xx,.. } from "./action-type";
	
	(2)创建并暴露函数,初始值可以在跟组件的useReducer中定义
		export function xxx(state=0,action)
		{
		    switch(action.type)
		    {
		        case xx:
		        return 操作
		        case xx:
		        return 操作
		        default: //初始状态
		        return state; 可在形参中设定初始值
		    }
		}
		
4、在根组件中使用useReducer

	(1)引入reducer和useReducer
		import React,{useReducer} from 'react';
		import reducer from '../reducer/reducers.js'
		
	(2)创建Context上下文,用于组件之间传递管理的状态和dispatch方法
		export const xx= React.createContext(null);
		
	(3)Context上下文存储状态和dispatch方法
		
		function App() {
		
		    const [state, dispatch] = useReducer(reducer, 初始状态);
		    
		    return (
		        将dispatch方法和状态都作为context传递给子组件
		        <xx.Provider value={{state,dispatch}}>
						子组件
		        </xx.Provider>
		    )
		}
		
5、子组件获取跟组件中的Context上下文对象,从而能获取和改变仓库的状态

	(1)引入跟组件中的上下文对象和其他Hook还有action
		import {xx} from "../App";
		import {x,x,...} from '../reducer/actions';
		import React, {useContext, useEffect,useState} from 'react';
		
	(2)使用仓库数据和管理仓库数据
	
		export default function App2() {
		
		    获取根组件的上下文
		    const xxx = useContext(xx);
		    
		    接收仓库管理的状态
		    let [state,setState]=useState(任意值);		
			
			
		    具有异步调用副作用的useEffect,或者单独抽离成一个模块,用于异步获取数据并放进仓库
		    useEffect(() => {

		            axios.get(url)
		                .then(res=>{
		                
		                    获取到数据后分发一个action,通知reducer更新状态
		                    xxx.dispatch(x(res.data))
		                    
		                    接收仓库的状态
		                    state=xxx.state;
		                })
		     
		    },[state]); 每当state改变,就更新仓库状态
		
		    return (
				<div>
					内容
				</div>
		    )
		}

单文件使用:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值