How to set object in state arrays from dynamic form in React

时光怂恿深爱的人放手 提交于 2020-05-30 08:47:45

问题


I am building a react app. I have created a dynamic form (generates X number of input fields (1-10) based on the number chosen by the user).That part works perfectly. However, I am wanting to add a second input field inside my mapping function. For context, I am building a flash card app. I want to add the term and the definition to the same state item. The idea is that each state array will hold an object for the term and an object for the definition in order to keep each definition with its proper term. Notice that the state items are named after the index of my mapping function. So for example, I want to send the term and definition to this.state.0 for the first term, etc... for each term and definition depending on how many the user wants to add (up to 10). Right now I'm getting the following error:

TypeError: Cannot read property 'term' of undefined

So how do I set each term and its definition to the state array, each to their own object of the array? Here is my component:

import React, { Component } from 'react'

export class TermForm extends Component {
    state = {
        0: [],
        1: [],
        2: [],
        3: [],
        4: [],
        5: [],
        6: [],
        7: [],
        8: [],
        9: []
    }

    onChange = (event) => this.setState({ [event.target.name]: event.target.value});

    render() {
        console.log(this.props.numberOfTerms);
        return (
            this.props.numberOfTerms.map((i) => (
                <div key={i}>
                    <input type="text" name={i.term} placeholder="TERM" value={this.state.i.term} onChange={this.onChange}></input>
                    <input type="text" name={i.def} placeholder="TERM" value={this.state.i.def} onChange={this.onChange}></input>
                </div>
            ))
        )
    }
}

export default TermForm

Any ideas about how I could set the object of a state array through my mapping function? Thanks in advance for any assistance.


回答1:


Cannot read property 'term' of undefined coz there is no such field on that location

value={this.state.i.term}

As per your initial state, it should look like this :

value={this.state.i[0]?.term}

The same change will be applicable for your def field also


Suggestion :

You should change the state something like this :

state = [
    {
        term : "" ,
        def : ""
    },
    {
        term : "" ,
        def : ""
    },
    ...
]

Then you can use it like this :

value={this.state[i].term}


来源:https://stackoverflow.com/questions/61966363/how-to-set-object-in-state-arrays-from-dynamic-form-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!