太多的重新渲染。React 限制渲染次数以防止无限循环错误

IT技术 reactjs react-native
2021-05-28 10:58:50

我正在尝试创建一个登录表单,但出现此错误。

export default function LoginScreen(props) {
        const [Submit, setSubmit] = React.useState('')
        const windowWidth = Dimensions.get('window').width
        const windowHeight = Dimensions.get('window').height
        const [valuePass, setValuePass] = React.useState('')
        const [valueUsername, setValueUsername] = React.useState('')
        const [secureTextEntry, setSecureTextEntry] = React.useState(true)
    
        const toggleSecureEntry = () => {
            setSecureTextEntry(!secureTextEntry)
        }
        const AlertIcon = (props) => <Icon {...props} name='alert-circle-outline' />
        const renderIcon = (props) => (
            <TouchableWithoutFeedback onPress={toggleSecureEntry}>
                <Icon {...props} name={secureTextEntry ? 'eye-off' : 'eye'} />
            </TouchableWithoutFeedback>
        )
    
        return (
            <View>
                <Text>Login</Text>
                <Input
                    placeholder='Username'
                    value={valueUsername}
                    style={{ width: windowWidth - 50, borderRadius: 16 }}
                    onChangeText={(nextValue) => setValueUsername(nextValue)}
                    size='large'
                />
                <View style={{ height: 15 }}></View>
                <Input
                    style={{ width: windowWidth - 50, borderRadius: 16 }}
                    size='large'
                    value={valuePass}
                    placeholder='Password'
                    caption='Should contain at least 8 symbols'
                    accessoryRight={renderIcon}
                    captionIcon={AlertIcon}
                    secureTextEntry={secureTextEntry}
                    onChangeText={(nextValue) => setValuePass(nextValue)}
                />
                <View style={{ marginTop: 25 }}>
                    <Button
                        style={{ borderRadius: 15 }}
                        onPress={setSubmit(true)}
                        size='large'
                    >
                        Submit
                    </Button>
                </View>
            </View>
        )
    }

谁能解释为什么会发生这个错误?

我是本机react的新手。

忽略这个(只是为了增加音量)==我必须添加一些无用的句子,因为 StackOverflow 给了我'It looks like your post is mostly code; please add some more details.'(对这个 stackoverflow 错误感到很沮丧)

2个回答

问题出在你的 onPress props上

onPress={setSubmit(true)}

花括号之间的所有内容都会立即计算。因此,在每个渲染循环中都会调用 setSubmit 函数。

通过用箭头函数包装函数,计算出的代码将产生一个函数,只要用户点击按钮就可以调用该函数。

所以应该是

onPress={()=>{setSubmit(true)}}

对于 Button 的 onPress props,您应该传递一个函数而不是直接传递一个实例。我的意思是这个;

<Button onPress={() => setSubmit(true)} />

做同样与<TouchableWithoutFeedback>也。

发生的事情是onPress在安装组件时进行检查,并且在您调用setSubmit一次又一次地更改状态,但是当您传递一个函数并在那里执行这些操作时,它会等待单击onPress以进行回调按下按钮时调用的函数。