代码之家  ›  专栏  ›  技术社区  ›  briankwlin

React Native中的Modals导致无限while循环

  •  1
  • briankwlin  · 技术社区  · 7 年前

    我只是想知道为什么下面的代码片段会导致无限的while循环,同时导致我的模拟器挂起,并出现错误“超过了最大更新深度。当组件在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 回复  |  直到 7 年前
        1
  •  1
  •   Marcos Demétrio    6 年前

    你能试试把你的钮扣改一下吗?

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

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

        2
  •  0
  •   asubanovsky    7 年前

    应该是:

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