【问题标题】:Modals in React Native resulting in infinite while loopReact Native 中的模态导致无限循环
【发布时间】:2017-12-17 23:25:23
【问题描述】:

我只是想知道为什么下面的代码 sn-p 会导致无限的 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',
    },
})

【问题讨论】:

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


    【解决方案1】:

    你能在你的按钮上试试这个改变吗?

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

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

    【讨论】:

      【解决方案2】:

      应该是:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-01
        • 1970-01-01
        • 2021-02-13
        • 2021-02-19
        • 2019-09-13
        • 1970-01-01
        • 2022-09-30
        • 2015-06-19
        相关资源
        最近更新 更多