【问题标题】:React-Native useCallback hook problemsReact-Native useCallback 钩子问题
【发布时间】:2020-08-09 14:59:05
【问题描述】:

我试图在用户按下提交时提醒他们他们根据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>
    }
}

【问题讨论】:

    标签: javascript react-native react-hooks


    【解决方案1】:

    你在handleSubmit上触发的useEffect是在handleSubmit定义之前定义的

    【讨论】:

    • 如果我将useEffect 放在handleSubmit 函数下,它不会无限渲染
    【解决方案2】:
    1. 你必须在handleSubmit函数之后编写useEffect钩子

    2. 今天和明天都使用 toggleHandler 函数

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

    【讨论】:

    • 如果我将useEffect 放在handleSubmit 函数下,它不会无限渲染
    猜你喜欢
    • 2020-05-03
    • 2022-08-19
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 2019-09-21
    • 2020-04-10
    • 2020-03-07
    • 1970-01-01
    相关资源
    最近更新 更多