【问题标题】:Undefined properties in dynamic form动态形式的未定义属性
【发布时间】:2022-01-15 16:43:19
【问题描述】:

新手问题,我在以下代码中收到TypeError: Cannot read properties of undefined (reading 'id')。我是否正确传递了道具?为什么这个值是未定义的?我的getValues 按钮返回一个空列表,其中length 属性为0,那么为什么在创建并传递给子组件时这是未定义的?

InputScreen.js

import React, { useState } from 'react';
import { v4 as uuidv4 } from 'uuid';
import { View, StyleSheet, ScrollView, FlatList } from 'react-native';
import { Button, Caption } from 'react-native-paper';
import InputCard from '../components/InputCard';

const InputScreen = props => {
    const [formState, setFormState] = useState([]);
    
    const addInput = () => {      
        setFormState([
            ...formState,
            {
                id: formState.length,
                substance: "",
                amount: "",
                measure: ""
            },
        ]);
    };

    const handleInputChange = (index, newStateForIndex) => {
        let newFormState = [...formState];
        setFormState([
            ...newStateForIndex.slice(0,index),
            newStateForIndex,
            ...newStateForIndex.slice(index+1)
        ]);
    };
    
    const removeLastInput = () => {
        if (formState.length > 0) {
            const lastindex = formState.length - 1;
            setFormState(formState.filter((item, index) => index !== lastindex));  
        }
    };

    const getValues = () => {
        console.log('Form State: ',formState,'Length: ',formState.length);
    };

    return (
        <ScrollView>
            <View style={styles.col}>
                <View style={styles.row}>
                    <Caption>What substances are you checking out?</Caption>
                </View>
                <View style={styles.row}>
                    <View>
                        {formState.map((state, i) => 
                            <InputCard
                                key={uuidv4()}
                                formState={state[i]}
                                handleChange={handleInputChange}
                            />
                        )}
                    </View>
                </View>
                <View>
                    <View style={styles.col}>
                        <Button title='Add' onPress={addInput}>Add</Button>
                    </View>
                    <View style={styles.col}>
                        <Button title='Remove' onPress={removeLastInput}>Remove</Button>
                    </View>
                    <View style={styles.col}>
                        <Button title='GetVals' onPress={getValues}>Get Values</Button>
                    </View>
                </View>
            </View>
        </ScrollView>
    );
};

export default InputScreen;

InputCard.js

import React from "react";
import { View, StyleSheet } from 'react-native';
import { Caption, Card, TextInput } from "react-native-paper";

const InputCard = ({ formState, handleChange }) => {
    
    const id = formState.id; // <- Error occurs here
    
    return (
        <View>
            <Card>
                <Card.Content>
                    <Caption>Item {id}</Caption>
                    <View style={styles.row}>
                        <View style={styles.half}>
                            <TextInput
                                label="substance"
                                value={formState.substance}
                                onChangeText={(event) => {
                                    handleChange(
                                        id,
                                        {
                                            ...formState,
                                            substance: event.target.value
                                        });
                                }} // change needs to be made from here to parent
                                mode="outlined"
                                right={<TextInput.Icon name="pill" />}
                                style={styles.textfield}
                            />
                        </View>
                        <View style={styles.quarter}>
                            <TextInput
                                label="amount"
                                value={formState.amount}
                                onChangeText={(event) => {
                                    handleChange(
                                        id,
                                        {
                                            ...formState,
                                            substance: event.target.value
                                        });
                                }}
                                mode="outlined"
                                keyboardType="number-pad"
                            />
                        </View>
                        <View style={styles.quarterlast}>
                            <TextInput
                                label="measure"
                                value={formState.measure}
                                onChangeText={(event) => {
                                    handleChange(
                                        id,
                                        {
                                            ...formState,
                                            substance: event.target.value
                                        });
                                }}
                                mode="outlined"
                            />
                        </View>
                    </View>
                </Card.Content>
            </Card>
        </View>
    );
};

export default InputCard;

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

    您的formState 表示一个包含对象的数组,因此在循环内,您的第一个参数是该数组的一个元素,它是一个对象,您不需要为它使用索引。

    <View>
      {formState.map((state, i) => 
         <InputCard
           key={uuidv4()}
           formState={state} // <- pass state instead of state[i]
           handleChange={handleInputChange}
          />
      )}
    </View>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-22
      • 2014-06-16
      • 1970-01-01
      • 2019-02-13
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多