React Native use回调挂钩问题



当用户按下submit时,我试图提醒他们根据CheckBox选择了什么选项。

我遇到的问题是,当我选中todaytomorrow复选框时,handleSubmit函数外的实际状态为true,而在handleSubmit函数中,todaytomorrow都为false,我不知道如何在useCallBack钩子中获得要呈现的实际状态。

请有人看到我哪里出了问题并帮助我。谢谢!!!

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

您的useEffect在定义handleSubmit 之前定义了handleSubit上的触发器

  1. 您必须在处理提交函数之后编写useEffect钩子

  2. 将toggleHandler函数用于toggle&明天

    setState(prev => !prev)
    
  3. 对这两种情况都使用if语句,因为您有复选框而不是单选按钮,所以有可能两个复选框都被选中。

最新更新