React中有条件调用hooks的方法吗? [重复]

问题描述 投票:0回答:4

我想根据一个变量调用不同的钩子...这个值来自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)
}
javascript reactjs
4个回答
8
投票

您需要为每个场景创建另外 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} />

if (productType === 'otherType')
  return <UseHookTwo accountId={accountId} statementId={statementId} />

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

1
投票

钩子不能被调用到函数或条件中

在根部使用 hook 并为每个 Hook 放置条件。

你能预测你的代码的用途吗?我认为代码的逻辑设计应该从不同的角度来看待

编辑示例:

// 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

}

0
投票
    useHookOne('x', 'y', prodType === "firstType")
    useHookTwo('x', 'y', prodType === "secondType")
    useHookOne('x', 'y', prodType === "thirdType"
    
    
    
    const useHookOne = (a,b,enabled)=> {
      if (!enabled) return;
     // Write core logic below

    }

    const useHookTwo = (a,b,enabled)=> {
      if (!enabled) return;
     // Write core logic below

    }
   
    const useHookThree = (a,b,enabled)=> {
      if (!enabled) return;
     // Write core logic below

    }

-1
投票

您可以使 useHookOne 返回一个带有两个参数 accountId 和 statementsId 的函数。

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.