如何解决错误“重新渲染太多。React 限制渲染次数以防止无限循环。”在反应原生?

时间:2021-04-03 20:41:00

标签: forms react-native

我已经开发了通过选择产品舞会选择器来提交投诉的表格。所以我在外部实现了选择器,然后在投诉提交表单中使用它。为此,我需要通过使用函数句柄更改将 selectedValue 状态带入投诉提交表单。在我实施该派系并更改有关教程链接的适当位置后:[https://github.com/reactjs/reactjs.org/issues/1689][1]

但是当我导航到投诉提交表单时,它显示错误为“Error: Too many re-renders. React limits the number of renders to prevent an infinite loop."所以请帮我解决,请确认我是否正确地遵循了上述教程。

投诉提交表:

import * as React from 'react';
import {Button, View, Text, ScrollView, StyleSheet, Alert} from 'react-native';
import {Appbar} from 'react-native-paper';
import {TextInput, HelperText} from 'react-native-paper';
import {useEffect, useState} from 'react';
import AsyncStorage from '@react-native-community/async-storage';
import ProductPicker from './ProductPicker';

const ComplaintSubmission = ({navigation}) => {

    const [productID , setproductID] = useState('');
    const [description , setdescription] = useState('');
    const [token, setToken] = useState('');


    useEffect(() => {
        saveToken();

    }, []);

function handleChange(newValue){
    setproductID(newValue);
}

    const saveToken = async () => {
        const token = await AsyncStorage.getItem('userToken');
        console.log('token from storage', token);
        setToken(token);
    }

    const send = () =>{

        fetch("http://10.0.2.2:3000/customer/lodge-complaint", {

            method: "post",
            headers: {
                'Content-Type': 'application/json',
                'Authentication': `Bearer ${token}`
            },
            body: JSON.stringify({

                description : description,
                productID : value

            })

        })

    }

    const openAlert = () => {
        Alert.alert(
            "Complaint Successfully Submitted",
            "We review it as soon as possible. Thank you for reaching for us!",
            [{
                text: "OK",
                onPress : () => navigation.navigate("DashboardDrawer" ),
            }]
        );
    }

  return (
    <ScrollView>

      <Appbar.Header>
        <Appbar.BackAction onPress={() => navigation.goBack()} />
        <Appbar.Content title="Submit Complaint" />
        <Appbar.Action icon="magnify" onPress={() => navigation.openDrawer()} />
      </Appbar.Header>

      <Text>Plese Fill the following</Text>

      <View>
          {/*{console.log('renderer token', token)}*/}
       <ProductPicker value={productID} onValueChange = {handleChange()} />
        <HelperText type="info">
          Make sure select the correct Product
        </HelperText>
      </View>

      <TextInput
        style={styles.PIDstyle}
        label="Description"
        onChangeText = {(description) => setdescription(description)}
      />
      <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
        <Text>This is submittion</Text>
        <Button onPress={() => {send(); openAlert();}} title="Submit Complaint" />
      </View>
    </ScrollView>
  );
};
export default ComplaintSubmission;
const styles = StyleSheet.create({
  PIDstyle: {
    marginTop: 30,
    marginLeft: 10,
    marginRight: 10,
  },
});

这是选择器组件:

import React, {useEffect, useState} from 'react';
import {View, StyleSheet} from 'react-native';
import {Picker} from '@react-native-picker/picker';
import AsyncStorage from '@react-native-community/async-storage';


const ProductPicker = () => {
    const [selectedValue, setSelectedValue] = useState('');
    const [productDetails, setproductDetails] = useState([]);
console.log('product id---', selectedValue);



    useEffect(() => {
        getProductList();
    }, []);

    function handleChange(event){
        props.onValueChange(event.target.value);
    }

    const getProductList = async () => {
        const token = await AsyncStorage.getItem('userToken');
        console.log(' function eka athule------', token);

        fetch('http://10.0.2.2:3000/customer/get-all-products', {

            method: 'post',
            headers: {
                'Content-Type': 'application/json',
                'Authentication': `Bearer ${token}`,
            },
        })
            .then((response) => response.json())
            .then((json) => setproductDetails(json.data))
            .catch((error) => console.error(error));
    };

    return (

        <View style={styles.container}>
            <Picker
                selectedValue={selectedValue}
                style={{height: 40, width: 150}}
                onValueChange={(itemValue, itemIndex) => {
                    setSelectedValue(itemValue);
                    handleChange();
                }}

            >


                {productDetails.map((item, index) => {
                    return (
                        <Picker.Item label={item.productName} value={props.item.productID} key={index}/>);

                })}

            </Picker>

        </View>

    );

};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingTop: 40,
        alignItems: 'center',
    },
});

export default ProductPicker;

1 个答案:

答案 0 :(得分:1)

为什么不将 itemValue 传递给 handleChange?

onValueChange={(itemValue, itemIndex) => {
                    setSelectedValue(itemValue);
                    handleChange(itemValue);
                }}

然后改变函数:

function handleChange(value){
        props.onValueChange(value);
    }