React-Native:永久违反:超过最大更新深度

时间:2019-07-25 14:47:41

标签: loops react-native input setstate native-base

我有一个以下登录屏幕,在将react-native更新为0.60.4之前可以正常使用。

interface OwnProps {
    navigation: any
}

interface StateProps {
    isLoggedIn: boolean,
    isAuthenticating: boolean
}

interface DispatchProps {
    actions: {
        auth: {
            authenticate: (username: string, password: string) => Promise<void>
        }
    }
}

type Props = OwnProps & StateProps & DispatchProps
interface State {
    username: string,
    password: string,
    error?: string,
    fadeAnim: Animated.Value
}

class LoginScreen extends Component<Props, State> {
    static propTypes = {
        isLoggedIn: PropTypes.bool.isRequired,
        isAuthenticating: PropTypes.bool.isRequired,
        actions: PropTypes.shape({
            auth: PropTypes.object
        })
    }

    state: State = {
        username: '',
        password: '',
        error: null,
        fadeAnim: new Animated.Value(1)
    }

    keyboardDidShowListener: EmitterSubscription
    keyboardDidHideListener: EmitterSubscription

    constructor(props) {
        super(props)

        this._onLogin = this._onLogin.bind(this)
        this._handleUsernameChange = this._handleUsernameChange.bind(this)
        this._handlePasswordChange = this._handlePasswordChange.bind(this)
    }

    componentDidMount() {
        this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow)
        this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide)
    }

    componentWillUnmount(): void {
        this.setState({
            username: '',
            password: null,
            error: null,
            fadeAnim: new Animated.Value(1)
        })

        this.keyboardDidShowListener.remove()
        this.keyboardDidHideListener.remove()
    }

    _keyboardDidShow = (): void => {
        Animated.timing(
            this.state.fadeAnim,
            {
                toValue: 0,
                duration: 500
            }
        ).start()
    }

    _keyboardDidHide = (): void => {
        Animated.timing(
            this.state.fadeAnim,
            {
                toValue: 1,
                duration: 500
            }
        ).start()
    }

    _onLogin = (): void => {
        dismissKeyboard()

        if (this.isFormValid()) {
            this.props.actions.auth.authenticate(this.state.username, this.state.password)
                .catch((error: Error) => {
                    const message: string = error ? error.message : 'Si e\' verificato un errore.'
                    this.setState({ error: message })
                    Toast.error(error.message)
                })
        }
    }

    isFormValid(): boolean {
        this.setState({ error: null })

        if (!this.state.username || this.state.username === '') {
            this.setState({ error: 'Username non valido.' })
            Toast.error('Username non valido.')
            return false
        }

        if (!this.state.password || this.state.password === '') {
            this.setState({ error: 'Password non valida.' })
            Toast.error('Password non valida.')
            return false
        }

        return true
    }

    _handleUsernameChange = (username: string) => {
        this.setState({ username })
    }

    _handlePasswordChange = (password: string) => {
        this.setState({ password })
    }

    render(): JSX.Element {
        const { fadeAnim } = this.state

        return (
            <Content
                padder
                style={styles.content}
                contentContainerStyle={styles.contentContainer}
                keyboardShouldPersistTaps='always'
                keyboardDismissMode='on-drag'
            >
                <TouchableWithoutFeedback onPress={dismissKeyboard}>
                    <View style={styles.contentContainer}>
                        <Spinner visible={this.props.isAuthenticating} textContent={'Accesso in corso...'} textStyle={{color: 'white'}} />

                        <Animated.View style={[styles.logosContainer, { opacity: fadeAnim }]}>
                            <Image
                                style={styles.logo}
                                source={require('../../assets/logo.png')}
                            />
                        </Animated.View>

                        <Form style={styles.form}>
                            <Item floatingLabel error={this.state.error ? true : false}>
                                <Label>Username</Label>
                                <Input
                                    autoCapitalize='none'
                                    autoCorrect={false}
                                    value={this.state.username}
                                    onChangeText={this._handleUsernameChange}
                                />
                            </Item>
                            <Item floatingLabel error={this.state.error ? true : false}>
                                <Label>Password</Label>
                                <Input
                                    autoCapitalize='none'
                                    autoCorrect={false}
                                    secureTextEntry
                                    value={this.state.password}
                                    onChangeText={this._handlePasswordChange}
                                />
                            </Item>
                        </Form>

                        {/*this.state.error ? (<FormMessage message={this.state.error} />) : null*/}

                        <Button block success style={styles.loginButton} onPress={this._onLogin}>
                            <Text>Accedi</Text>
                        </Button>
                    </View>
                </TouchableWithoutFeedback>
            </Content>
        )
    }
}

[...]

export default connect(mapStateToProps, mapDispatchToProps)(LoginScreen)

更新后,当我尝试输入用户名或密码时,会引发以下期望:

  

不变违反:超出最大更新深度。当组件重复调用componentWillUpdate或componentDidUpdate内部的setState时,可能会发生这种情况。 React限制了嵌套更新的数量,以防止无限循环。

我在堆栈溢出和互联网上读了很多问题,但是似乎没有什么可以解决问题。

有人可以帮我吗?

2 个答案:

答案 0 :(得分:0)

componentWillUnmount()在卸载和销毁组件之前立即被调用。用这种方法执行任何必要的清除,例如使计时器无效,取消网络请求或清除在componentDidMount()中创建的所有订阅。

您不应在setState()中调用componentWillUnmount(),因为组件将永远不会被重新渲染。卸载组件实例后,将永远不会再次安装它。

您可以在setState()中删除componentWillUnmount()

    componentWillUnmount(): void {

        this.keyboardDidShowListener.remove()
        this.keyboardDidHideListener.remove()
    }

答案 1 :(得分:0)

不知道为什么,但是升级到最新的react-navigation版本后,一切都可以正常工作。