![](/img/trans.png)
[英]How to use a custom-hook that returns a value, inside another custom Hook?
[英]How to make Custom Hook returns a function, which uses another hook
所以我有一個自定義鈎子,我想在另一個組件的多個地方使用它,比如一個函數,它接受參數 (Ei For useNavigate()
from react-router-dom-v6
,我們將它用作const navigate = useNavigate()
然后navigate('./url/to/navigate')
可以在多個地方使用)。
但是在自定義掛鈎中,我想通過另一個自定義掛鈎處理該參數值。 這是我嘗試過的,但 React 不允許我在函數內部有這樣的鈎子:
//useCustomHook.js
function usePrevious(value) {
const ref = useRef();
useEffect(() => {
ref.current = value;
});
return ref.current;
}
...
export default function useCustomHook() {
function processingData(currentState){
const previousState = usePrevious(currentState); //React does not allow to have hook here
return process(currentState, previousState);
}
return processingData;
}
//Component.js
...
const cusHook = useCustomHook();
...
useEffect(()=>{
cusHook(state1)
},[])
useEffect(()=>{
cusHook(state2)
},[temp])
有沒有辦法可以做到這一點?
不,您無法在純 JavaScript 函數中使用鈎子。 為什么不做這樣的事情:
export default function useCustomHook(currentState) {
const previousState = usePrevious(currentState);
const processingData = () => {
return process(currentState, previousState);
}
return processingData;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.