react学习与使用

react学习与使用 1.useState用法1.1.基本数据类型//实时获取值const[count,setCount]useState(0);useEffect((){console.log(count);},[count]);consthandleClick(){setCount(countcount1)}1.2.引用数据类型//useState返回一个数组,数组里有两项const[myState,setMyState]useState({curNodeName:,recordVisible:false});const[arr,setArr]useState([{width:10,id:0}]);constupdateMyStatedata{setMyState({...myState,...data});};constdealState(nodeId:number){//改变对象里的值updateMyState({recordVisible:true})//增加setArr([...arr,{width:10,id:count1}]);//删除setArr(arr.filter((item,i)i!index));// 修改索引为index的元素setArr(arr.map((item,i)iindex?{...item,width:newWidth,id:newId}:item));}2.redux用法reducers用于同步更新状态reducer 通过接受 action 来更新状态。 effects处理异步操作通过yield关键字来进行异步请求结合select,call,put使用。 dispatch触发同步和异步的 actiondispatch 会通知 reducer 或 effect 执行相应的操作。exportdefault{namespace:myModel,// 模块唯一标识页面dispatch必须带上state:{tableList:[],current:1,pageSize:10,totalNum:0,},reducers:{// 同步更新statepayload可以传tableList/current/total等多个字段setTableList(state,{payload}){return{...state,// 保留原有state其他字段...payload// 覆盖传入的字段}}},effects:{// 异步方法* 生成器yield 阻塞等待异步完成*getList({payload},{select,call,put}){// 1. select 获取当前 myModel 下的 state示例本逻辑没用到conststateyieldselect(statestate[myModel])// 2. call 发起接口请求payload是页面传过来的分页参数constresponseyieldcall(getTableList,payload);// 3. put 派发同步action执行reducer里的setTableList更新页面状态yieldput({type:setTableList,payload:{tableList:Object.assign([],response.data.records),current:Number(response?.data?.current)||1,pageSize:Number(response?.data?.size)||10,totalNum:Number(response?.data?.total)||0,}})}},subscriptions:{},// 监听路由/浏览器事件这里没用到留空};//页面使用时import{useSelector,useDispatch}fromreact-redux;constdispatchuseDispatch();dispatch({type:myModel/getList,payload:{}});//页面获取值时constselectoruseSelector(statestate[myModel])3.父子组件传值3.1.父传子(props)//父组件importReactfromreact;importChildComponentfrom./ChildComponent;constParentComponent:React.FC(){// 定义需要传递的数据constmessage这是来自父组件的数据;// 定义需要传递的方法consthandleClick(){console.log(按钮被点击了);};return(div{/* 传递数据和方法给子组件 */}ChildComponent text{message}onClick{handleClick}//div);};//子组件importReactfromreact;interfaceChildProps{text:string;onClick:()void;}constChildComponent:React.FCChildProps(props){return(divp{props.text}/pbutton onClick{props.onClick}点击我/button/div);};3.2.子传父(ref)//父组件不管是类还是函数组件都支持creatRef()函数组件可以用useRef();//子组件中函数组件由于没有实例只能使用forwardRef搭配useImperativeHandle使用importReact,{useImperativeHandle,forwardRef}fromreact;constfocusInput(){console.log(Input is focused);}constChildComponentforwardRef((props,ref){useImperativeHandle(ref,(){return{focusInput}});});//子组件importReact,{useRef}fromreact;importChildComponentfrom./ChildComponent;functionParentComponent(){constchildRefuseRef(null);consthandleClick(){if(childRef.current){childRef.current.focusInput();// 调用子组件的方法}};return(divChildComponent ref{childRef}/button onClick{handleClick}Focus Input/button/div);}3.3子组件改变父组件的值1.通过回调函数的方式// 父组件importReact,{useState}fromreact;importChildComponentfrom./ChildComponent;constParentComponent(){const[parentValue,setParentValue]useState();// 定义更新父组件状态的函数constupdateParentValue(newValue){setParentValue(newValue);};return(divp父组件的值:{parentValue}/p{/* 将更新函数作为prop传递给子组件 */}ChildComponent onUpdateValue{updateParentValue}//div);};// 子组件constChildComponent({onUpdateValue}){consthandleChange(event){// 调用父组件传递的函数更新父组件的值onUpdateValue(event.target.value);};return(input typetextplaceholder输入内容更新父组件的值onChange{handleChange}/);};2.通过context的方式importReact,{createRef,createContext,useState}fromreact;importTablePagefrom./table;// 父组件ProviderexportconstValueContextcreateContextany(null);constEntry:React.FCanyprops{const[parentValue,setParentValue]useState();constvalueContextValue{parentValue,setParentValue};return(ValueContext.Provider value{valueContextValue}p父组件的值:{parentValue}/pTablePage//ValueContext.Provider);};exportdefaultEntry;//子组件importReact,{forwardRef,useContext}fromreact;import{ValueContext}from./index;classConfigSummaryProps{disabled?:boolean;[p:string]:any;}typeConfigSummaryRef{getEditData:()any;};constConfigSummaryforwardRefConfigSummaryRef,ConfigSummaryProps((props,ref){})//ts写法constTablePage:React.FCanyforwardRef((props,ref){const{parentValue,setParentValue}useContext(ValueContext);consthandleChange(event){setParentValue(event.target.value);};return(input typetextplaceholder输入内容更新父组件的值onChange{handleChange}//);});exportdefaultTablePage;