useContext
介绍
与class中写法对比减少了代码量,省去了返回回调函数获取传来的值
使用
*** useContext(减少组件层级)* impo
useContext
介绍
与class中写法对比减少了代码量,省去了返回回调函数获取传来的值
使用
/** * useContext(减少组件层级) */ import React, { useState, useRef, useContext } from 'react'; const GlobalContext=React.createContext()//创建Context对象 function FilmItem(){ const value=useContext(GlobalContext) console.log(value)//可以拿到传过来的value return( <div> <span>{value.name}CSDN碰磕</span> </div> ) } export default function MyContext() { return ( //供应商 <GlobalContext.Provider value={{ name:"碰磕", age:18 }}> <div> Context方案 <FilmItem></FilmItem> </div> </GlobalContext.Provider> ); }
通过**useContext(GlobalContext)**就可以获取到传来值
useReducer
介绍
将多个state放到对象中,进行统一管理
使用(简单示例实现计算器)
/** * useReducer(减少组件层级) */ import React, {useReducer } from 'react'; //处理函数 const reducer=(pervState,action)=>{ //第一个参数是原数据,第二个参数是传来的数据 let newarr={...pervState};//定义新对象拷贝 switch(action.type){ case "pengke-jian": newarr.count-- return newarr case "pengke-jia": newarr.count++ return newarr default: return pervState } } //外部的对象 const intialState={ count:0, } export default function MyReducer() { const [state,dispatch]=useReducer(reducer,intialState) return ( <div> <button onClick={()=>{ dispatch({ type:"pengke-jian" }) }}>-</button> <span>{state.count}</span> <button onClick={()=>{ dispatch({ type:"pengke-jia" }) }}>+</button> </div> ) }
将useContext与useReducer整合
实现多个组件通过他们俩互相通信传值…
/** * useReducer+useContext */ import React, {useContext, useReducer } from 'react'; const intialState={ num1:"666", num2:"碰磕" } const reducer=(state,action)=>{ let newarr={...state}; switch(action.msg){ case "change-num1": newarr.num1=action.value return newarr case "change-num2": newarr.num2=action.value return newarr default: return newarr } } const GlobalContext = React.createContext(); export default function MyReducer2() { const [state,dispatch]=useReducer(reducer,intialState) return ( <GlobalContext.Provider value={ { state,dispatch } }> <div> <Children1 /> <Children2 /> <Children3 /> </div> </GlobalContext.Provider> ) } function Children1(){ const {dispatch}=useContext(GlobalContext)//这里传值 return <div style={{background:"red"}}> <button onClick={()=>{ dispatch({ msg:"change-num1", value:"被我修改了num1哈哈哈" }) }}>改变值1</button> <button onClick={()=>{ dispatch({ msg:"change-num2", value:"被我修改了num2哈哈哈" }) }}>改变值2</button> </div> } function Children2(){ const {state}=useContext(GlobalContext)//拿到值 return <div style={{background:"orange"}}>Children2---{state.num1}</div> } function Children3(){ const {state}=useContext(GlobalContext)//拿到值 return <div style={{background:"skyblue"}}>Children3---{state.num2}</div> }
到此这篇关于React useContext与useReducer函数组件使用的文章就介绍到这了,更多相关React useContext与useReducer内容请搜索好代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好代码网!