Cri*_*rez 6 javascript reactjs
我想根据一个变量调用不同的钩子...这个值来自URL参数并且是动态的,但是钩子不能根据Hook的规则有条件地运行:
// 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)
}
Run Code Online (Sandbox Code Playgroud)
您需要为每个场景创建另外 3 个组件。在每个组件中,你可以添加自己的逻辑。
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} />
}
Run Code Online (Sandbox Code Playgroud)
然后创建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
Run Code Online (Sandbox Code Playgroud)
钩子不能被调用到函数或条件中
在根中使用钩子并为每个钩子设置条件。
您能预测代码的用途吗?我认为代码的逻辑设计应该从不同的角度来看待
编辑示例:
// this hook comes from react-router dom to get the URL params
const param = const { productType, accountId, statementId } = useParams();
let apiRequest = new productRequestAPI();
if(prodType == "firstType"){
apiQuest.adress = 'adress.api.com';
apiQuest.quest: 'firstRequest';
apiQuest.accountId ... etc
}
else if(prodType == "secondType"){
...
}
singleHook(apiRequest){
//Call API with good params and return after
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11345 次 |
| 最近记录: |