import React,{useState,useEffect} from 'react';
export const useStateHooks=(val:any)=>{
let [value,setValue]=useState(val);
const setFunc=(v:any)=>{
setValue(v);
return v;
}
return {
value,setFunc
};
}
import React,{useState,useEffect,useImperativeHandle,useCallback,useReducer} from 'react';
import {useStateHooks} from "../hooks/useStateHooks";
export const Test=()=>{
let obj=useStateHooks(1);
const change=()=>{
const newVal=obj.setFunc(obj.value+1);
console.log(obj.value,newVal);
}
return (
<div>
<span>数据:{obj.value}</span>
<button onClick={change}>改变</button>
</div>
)
}
这个函数肯能放在status内部执行,多有函数内部可以获取到最新值
注意,class组件和hooks都可以
如果将add改为先加1再加2,会发现代码只执行了最后一个加2,加1被忽略了,如:
1234 const add = () => { setCounter(counter + 1) setCounter(counter + 2)}
解决方法是将setState的参数写成函数形式
1234 const add = () => { setCounter(counter => counter + 1) setCounter(counter => counter + 2)}
标签:const,自定义,hooks,counter,useStateHooks,value,obj
From: https://www.cnblogs.com/Arborblog/p/16945389.html