React Native中的模态导致无限循环

时间:2017-12-17 23:25:23

标签: reactjs while-loop native react-native-android

我只是想知道为什么下面的代码段导致无限循环,同时导致我的模拟器挂起错误"超出最大更新深度。当组件在componentWillUpdate或componentDidUpdate"内重复调用setState时,可能会发生这种情况。

import React, { Component } from 'react';
import * as firebase from 'firebase';
import { ActivityIndicator, ListView, Modal, Text, View, Button, StyleSheet } from 'react-native';

export default class GroceryList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            modalVisible: false,
        };
    }

    render() {
        return(
            <View style={styles.container}>
                <Text>hi</Text>
                <Modal
                    visible = {this.setState({modalVisible: false})}
                    animationType={'slide'}
                    onRequestClose={this.setState({modalVisible: false})}
                >
                    <View style={styles.modalContainer}>
                        <View style={styles.innerContainer}>
                            <Text>This is content inside of modal component</Text>
                            <Button
                                onPress={this.setState({modalVisible: false})}
                                title="Add to cart"
                            />
                        </View>
                    </View>
                </Modal>
                <Button
                    onPress={this.setState({modalVisible: true})}
                    title="PURCHASE ITEM"
                    color="#841584"
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container:{
        flex: 1,
        justifyContent: 'center',
        marginTop: 50,
    },
    buttonContainer: {
        margin: 20,
    },
    modalContainer: {
        flex: 1,
        justifyContent: 'center',
        backgroundColor: 'grey',
        height: 20,
    },
    innerContainer: {
        alignItems: 'center',
    },
})

2 个答案:

答案 0 :(得分:1)

您可以在按钮中尝试此更改吗?

<Button
  onPress={() => this.setState({modalVisible: true})}
  ...
/>

您无法在渲染方法中直接使用this.setState()

答案 1 :(得分:0)

应该是:

<Modal
                visible = {this.state.modalVisible}
                animationType={'slide'}
                onRequestClose={this.setState({modalVisible: false})}
            >