【发布时间】:2020-08-10 12:06:38
【问题描述】:
当他们按下提交时,我试图提醒用户他们根据 CheckBox 选择的选项。
但是我遇到了一个问题,当我选中 today 和 tomorrow 的复选框时,handleSubmit 函数之外的实际状态为 true,但在 handleSubmit 函数中,today 和 tomorrow 均为 false而且我不知道如何在useCallBack 钩子中渲染实际状态。因此 useCallBack 中的 today 和 tomorrow 将始终为 false
请有人看看我哪里出错并帮助我解决这个钩子问题。谢谢!!!
import React, { useEffect, useState, useCallback } from 'react'
import { CheckBox } from 'react-native-elements'
import { Alert } from 'react-native'
const Choose = (props) => {
const [today, setToday] = useState(false)
const [tommorow, setTommorow] = useState(false)
useEffect(() => {
props.navigation.setParams({ handleSubmit: handleSubmit })
}, [handleSubmit])
console.log(`today is ${today}`) // this works and is changed by the check box
const handleSubmit = useCallback(() => {
if (today == true){
console.log(`today is ${today}`) // today from outise this function is never true
Alert.alert('You selected today')
}else if (tommorow == true){
Alert.alert('You selected tommorow')
}
}, [today, tommorow])
return (
<View>
<CheckBox
checked={world}
onPress={() => setToday(!today)}
title='Today'
/>
<CheckBox
onPress={() => setTommorow(!tommorow)}
title='Tommorow'
/>
</View>
)
}
export default ChooseToAdd
Choose.navigationOptions = () => {
const submit = navigationData.navigation.getParam('handleSubmit')
return {
headerRight: () =>
<TouchableOpacity onPress={submit}>
<Text>Submit</Text>
</TouchableOpacity>
}
}
【问题讨论】:
-
如果您重构代码以将 handleSubmit 的声明放在选择组件之外并完全放弃 useEffect 有什么不同吗?例如: const handlesubmit = (today, tomorrow) => { if (today == true){ console.log(
today is ${today}) // today from outise 这个函数永远不会为真 Alert.alert('You selected today') } else if (tommorow == true){ Alert.alert('You selected tommorow') } } -
是的,它无法访问今天和明天的状态
-
传递状态以便它可以访问它。
-
请告诉我,因为我真的不知道如何将状态传递给它。我真的很感激。谢谢
标签: reactjs react-native react-hooks