简体   繁体   中英

React Native- Getting Error: Too many re-renders. React limits the number of renders to prevent an infinite loop while showing modal

I have a service Details page, I want to open a modal when Add to Cart Button is clicked, however I am getting too many re-renders error, I have tried alot of different things but can't seem to fix it. Please help

This is the ServiceDetails function I am setting the state of cartmodalVisible to true on click of "Add to Cart" button and then passing that state as prop to CartModal

const ServiceDetailsScreen = ({navigation, route}) => {
  const [data, setData] = useState({});
  const [LabData, setLabData] = useState({});
  const [TestData, setTestData] = useState({});
  const [Service, setService] = useState({});
  const [cartmodalVisible, setcartmodalVisible] = useState(false);
  const [bookNowModal, setbookNowModal] = useState(false);
  const id = route.params.id;
  // console.log('id rececived', id);
  const getServiceDetails = async () => {
    try {
      console.log('id of service', route.params.id);
      const {data} = await axios.get(
        `${url}/Inventory/getServiceDetail/${id}`,
      );
      // console.log(' call sent');
      setData(data);

      setLabData(data.LabData);
      setTestData(data.TestData);
    } catch (error) {
      console.log(error);
      ToastAndroid.show('Something went wrong', ToastAndroid.SHORT);
    }
  };

  useEffect(() => {
    getServiceDetails();
  }, [id]);

  return (
    <View style={Styles.ServiceContainer}>
      <Cartmodal cartmodalVisible={cartmodalVisible} />
    
      <View style={Styles.Service}>
        <View style={Styles.Picture}>
          <View>
            <Image source={logo} style={Styles.Logo} />
          </View>
          <View style={{flexShrink: 1}}>
            <Text style={{fontSize: 18, flexShrink: 1}}>{LabData.name}</Text>
          </View>
        </View>
      </View>
      <View style={Styles.Service}>
        <View style={Styles.DetailsHeader}>
          <Text style={{fontWeight: 'bold', fontSize: 25}}>
            {' '}
            {data.ServiceTitle}
          </Text>
          <Text style={{fontWeight: '500', fontSize: 20}}>
            {' '}
            PKR: {data.ServicePrice}
          </Text>
        </View>
        <View style={Styles.RatingContainer}>
          <Rating imageSize={14} readonly startingValue={data.rating} />
        </View>
        <View style={Styles.DetailDescription}>
          <Text style={Styles.headings}>Description:</Text>
          <Text style={Styles.DetailDescriptionText}>
            {data.ServiceDescription}
          </Text>
        </View>
        <View style={Styles.DetailDescription}>
          <Text style={Styles.headings}>Pre Conditions:</Text>
          <Text style={Styles.DetailDescriptionText}>
            {TestData.PreConditions}
          </Text>
        </View>
        <View style={Styles.DetailDescription}>
          <Text style={Styles.headings}>Average Duration:</Text>
          <Text style={Styles.DetailDescriptionText}> {data.Duration}</Text>
        </View>
        <View style={Styles.DetailDescription}>
          <Text style={Styles.headings}>Additional Services:</Text>

          <View style={Styles.AdditionalServices}>
            <Text style={Styles.DetailDescriptionText}>
              {' '}
              Home Sampling:{' '}
              {data.HomeSampling == true ? (
                <Text Styles={{fontWeight: 'bold'}}>✓ </Text>
              ) : (
                <Text Styles={{fontWeight: 'bold'}}>✗ </Text>
              )}
            </Text>
            {data.HomeSampling == true ? (
              <Text style={Styles.PriceText}>
                {' '}
                PKR: {data.HomeSamplingPrice}
              </Text>
            ) : null}
          </View>
          <View style={Styles.AdditionalServices}>
            <Text style={Styles.DetailDescriptionText}>
              {' '}
              Communication:
              {data.Communication == true ? (
                <Text Styles={{fontWeight: 'bold'}}>✓ </Text>
              ) : (
                <Text Styles={{fontWeight: 'bold'}}>✗ </Text>
              )}
            </Text>
            {data.Communication == true ? (
              <Text style={Styles.PriceText}>
                {' '}
                PKR: {data.CommunicationPrice}
              </Text>
            ) : null}
          </View>
        </View>
        <Cartmodal cartmodalVisible={cartmodalVisible} />
        <View style={Styles.Buttons}>
          <Button
            type="solid"
            title="Book Now"
            buttonStyle={{
              backgroundColor: '#34C38F',
              borderColor: 'transparent',
              borderWidth: 0,
              paddingVertical: 7,
              borderRadius: 10,
            }}
            titleStyle={{fontWeight: '100'}}
            icon={{
              name: 'timer',
              type: 'FontAwesome',
              size: 20,
              color: 'white',
            }}></Button>

          <Button
            type="solid"
            title="Add To Cart"
            onPress={() => setcartmodalVisible(true)}
            buttonStyle={{
              backgroundColor: '#0154E0',
              borderColor: 'transparent',
              borderWidth: 0,
              paddingVertical: 7,
              borderRadius: 10,
            }}
            titleStyle={{fontWeight: '100'}}
            icon={{
              name: 'shopping-cart',
              type: 'MaterialIcons',
              size: 20,
              color: 'white',
            }}></Button>
        </View>
      </View>
    </View>
  );
};

export default ServiceDetailsScreen;

and this is my Modal

const Cartmodal = props => {
  const {cartmodalVisible} = props;
  const [visible, setVisible] = useState(cartmodalVisible);
  console.log('cartmodalVisible', cartmodalVisible);

    return (
      <Modal
        animationType="slide"
        transparent={true}
        visible={visible}
        onRequestClose={() => {
          setVisible(!visible);
        }}
        onDismiss={() => {
          setVisible(!visible);
        }}
      >
        <View style={modalstyles.centeredView}>
          <View style={modalstyles.modalView}>
            <View style={modalstyles.modalHeader}>
              <View style={modalstyles.modalHeaderContent}>
                <Text>Add to Cart</Text>
              </View>
              <TouchableOpacity onPress={setVisible(!visible)}>
                <Text style={modalstyles.modalHeaderCloseText}>X</Text>
              </TouchableOpacity>
            </View>
            <Text style={modalstyles.modalText}>Hello World!</Text>
            <Pressable style={[modalstyles.button, modalstyles.buttonClose]}>
              <Text style={modalstyles.textStyle}>Cancel</Text>
            </Pressable>
          </View>
        </View>
      </Modal>
    );
 
};

Your problem is in CartModal component

change this

<TouchableOpacity onPress={setVisible(!visible)}>
    <Text style={styles.modalHeaderCloseText}>X</Text>
</TouchableOpacity>

to this

<TouchableOpacity onPress={() => setVisible(!visible)}>
    <Text style={styles.modalHeaderCloseText}>X</Text>
</TouchableOpacity>

TouchableOpacity onPress is running multiple times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM