javascript - How to set state to an array of objects in react - Stack Overflow

I am working on a flash card react application. I have initialized my state as an array of objects (the

I am working on a flash card react application. I have initialized my state as an array of objects (the user can only add up to 10 terms/definitions at a time so limited to 10) as follows:

state = { 
        allTerms: [
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        }
    ]
}

The input es from a dynamic form that provides X number of input fields based on the number of cards the user wanted to add. My current problem is my onChange function. When a user types something in an input field (right now focused on the term and figure I can use a similar solution for definition) the change calls my onChangeTerm function where I have a for loop:

onChangeTerm = (event) => {

        for(var i = 0; i < this.props.numberOfTerms.length; i++) {
            this.setState({ allTerms[i].term: event.target.value});
        }
    }

I am having trouble with the setState line. My idea was that allTerms is my array that is in state. I want to set the value from the event (input from user) to the i element (increases as the for loop runs in the situation the user is wanting to add multiple cards) of the array, and specifically to the property of term in each object. However, I get a failed to pile error. Why is this setState line not working? My logic makes sense to me, but I seem to be missing something...is my syntax messed up? Or is there a piece the logic I am missing when it es to setting state for an array of objects? Thanks for any ideas.

I am working on a flash card react application. I have initialized my state as an array of objects (the user can only add up to 10 terms/definitions at a time so limited to 10) as follows:

state = { 
        allTerms: [
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        },
        {
            term: '',
            def: ''
        }
    ]
}

The input es from a dynamic form that provides X number of input fields based on the number of cards the user wanted to add. My current problem is my onChange function. When a user types something in an input field (right now focused on the term and figure I can use a similar solution for definition) the change calls my onChangeTerm function where I have a for loop:

onChangeTerm = (event) => {

        for(var i = 0; i < this.props.numberOfTerms.length; i++) {
            this.setState({ allTerms[i].term: event.target.value});
        }
    }

I am having trouble with the setState line. My idea was that allTerms is my array that is in state. I want to set the value from the event (input from user) to the i element (increases as the for loop runs in the situation the user is wanting to add multiple cards) of the array, and specifically to the property of term in each object. However, I get a failed to pile error. Why is this setState line not working? My logic makes sense to me, but I seem to be missing something...is my syntax messed up? Or is there a piece the logic I am missing when it es to setting state for an array of objects? Thanks for any ideas.

Share Improve this question asked May 23, 2020 at 6:07 Luke SharonLuke Sharon 2601 gold badge11 silver badges35 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 2

Here you go :

You can pass event and index both to the function :

Ref is taken from your prev question :

<input type="text" name={i.term} placeholder="TERM" 
value={this.state.allTerms[i].term} 
onChange={(e) =>this.onChange(e,i)}> // <--- Change
</input>

Update something like this :

onChangeTerm = (event , index) => {
    this.setState({
        allTerms : [
        ...this.state.allTerms.splice(0,index) ,
        {
            ...this.state.allTerms[index],
            term: event.target.value
        },
        ...this.state.allTerms.splice(index+1) ,
    });
}

Its bad idea to have your state updated inside a loop, I would suggest you use object spread operator and once you finished building the state object, you assign it to your ponent state:

onChangeTerm = (event) => {
  let allTerms = {}
  for(var i = 0; i < this.props.numberOfTerms.length; i++) {
    allTerms = { ...this.state.allTerms[i], term: event.target.value }
  }
  this.setState({ allTerms });
}

There are a couple of issues with your code:

  • update state in the loop is a bad idea -> might cause bad performance as it will render often
  • the first argument in setState is an object ({key: value}), if you want to use the dynamic key you must do {[dynamicKey]: value}
  • the state object is repetitive, I would build it dynamically

Here is a working example: code sandbox

Here you go : first, your input shall have and id

<input type="text" id = 'term'/>

second, your onChange function should be :

onChangeTerm = (e) =>  {
e.preventDefault();
 this.setState({ [e.target.id]: e.target.value}); 
 }

third, if you want many term inputs so don't repeat the same input with the same name. change your input name also in your state and don't put yourself in non-sensable for loop.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744821529a4595649.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信