【发布时间】:2020-09-28 10:59:28
【问题描述】:
有固定数量的设置决定组件是否应该可见,即:
const restrictions = {
isLogged: true, // TRUE stands for: check if the condition is met
hasMoney: true,
didWinYesterday: false,
}
对于每个restrictions 键,我使用useState 创建了一个状态并使用false 将它们全部初始化,例如:
const [isUserLogged, setIsUserLogged] = useState(false)
const [hasUserMoney, setHasUserMoney] = useState(false)
const [didUserWinYday, setDidUserWinYday] = useState(false)
接下来,我使用useEffect 检查每个条件并相应地更新状态:
useEffect(() => {
const checkIfUserIsLogged = async () => {
// calling an API to get boolean
const isLogged = await API.call()
setIsUserLogged(isLogged)
}
// If the restriction is set to false, ignore checking and set relevant state
if (!restrictions.isLogged) {
setIsUserLogged(true)
return
}
checkIfUserIsLogged()
}, [restrictions.isLogged])
最后,我正在检查是否应该渲染实际的组件,或者我应该像这样提前中断:
if (!isUserLogged) return <p>User not logged in.</p>
useEffect 代码和上面的检查一共重复了 3 次。每个重复都在进行不同的 API 调用并更新不同的状态,但整体结构保持不变。
我希望我能做得更干,但不知道如何开始。欢迎任何提示,谢谢!
【问题讨论】:
-
我认为您有一个逻辑问题,因为您将事物初始化为
false- 您不应该将它们初始化为undefined,因为您还不知道服务器状态,这可以是true或false?
标签: javascript reactjs react-hooks