我想根據一個變數呼叫不同的鉤子……這個值來自 URL 引數并且是動態的,但是鉤子不能根據鉤子的規則有條件地運行:
例子
// this hook comes from react-router dom to get the URL params
const param = const { productType, accountId, statementId } = useParams();
// I need to run a hook that calls a different API according productType value
if (productType === 'someType') {
return useHookOne(accountId, statementId)
} else if (productType === 'otherType') {
return useHookTwo(accountId, statementId)
} else {
return useHookThree(accountId, statementId)
}
uj5u.com熱心網友回復:
每個場景都需要其他組件。在每個組件中,您可以添加一個邏輯。
const param = const { productType, accountId, statementId } = useParams();
// I need to run a hook that calls a different API according productType value
if (productType === 'someType') {
return <UseHookOne accountId={accountId} statementId={statementId} />
} else if (productType === 'otherType') {
return <UseHookTwo accountId={accountId} statementId={statementId} />
} else {
return <UseHookThree accountId={accountId} statementId={statementId} />
}
然后創建 3 個新組件。示例與UseHookOne
import React from 'react'
const UseHookOne = (props) => {
const data = useHookOne(props.accountId, props.statementId)
return (<>Yay! Logic number 1 based on {data}</>)
}
export default UseHookOne
uj5u.com熱心網友回復:
鉤子不能被呼叫到函式或條件中
在根中使用鉤子并為每個鉤子放置條件。
你能預測你的代碼的目的嗎?我認為代碼的邏輯設計應該從不同的角度來處理
編輯示例:
// this hook comes from react-router dom to get the URL params
const param = const { productType, accountId, statementId } = useParams();
// HERE: logical bloc
let apiRequest = new productRequestAPI();
if(prodType == "firstType"){
apiQuest.adress = 'adress.api.com';
apiQuest.quest: 'firstRequest';
apiQuest.accountId ... etc
}
else if{
...
}
singleHook(oneSpecificRequestOfOneProduct){
//Call API with good params and return after
}
uj5u.com熱心網友回復:
您可以讓 useHookOne 回傳一個帶有兩個引數 accountId 和 statementId 的函式。
const setHookOne = useHookOne()
const setHookTwo = useHookTwo()
const setHookThree = useHookThree()
if (productType === 'someType') {
return setHookOne(accountId, statementId)
}else if (productType === 'otherType') {
return setHookTwo(accountId, statementId)
} else {
return setHookThree(accountId, statementId)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/360488.html
標籤:javascript 反应
上一篇:在javascript中使用createTextNode和createElement在標簽內添加文本時出現問題
下一篇:影片字母移除和容器大小
