简体   繁体   中英

ReactJS setState with object and array

I want to have a data structure in terms of array eg

data[0]
  title:"ABC"
  photo: "./123.jpg"
  summ: "text text test"
data[1]
  title:"ABCD"
  photo: "./1234.jpg"
  summ: "text texwt test"

I have attempted to setState like this, but it won't work. Please guide me ;(


             this.setState({
               data:{
                title: [ ...this.state.data.title, title ],
                photo: [ ...this.state.data.photo, photo ],
                summ: [ ...this.state.data.summ, summ ]   

                    }

                  });

Uncaught (in promise) TypeError: _this.state.data.concat is not a function

在此处输入图片说明

///// Mistake on not initialize my state

// this is incorrect
this.state={
data:{
title:null,
photo:null,
summ:null,
}
//The correct version is
this.state={
data:[],

The reason your solution doesn't work is that you are trying to assign an object to an array.

I am not sure if you are trying to add an item to array or change single item from an array. If you are trying to add, you can do it like this:

this.setState({
...this.state.data, {title, photo, summ}
})

However if you are trying to change an item from the array. You should store in a temporary variable and then assign it like this.

const tempArray = this.state.data;
this.setState({
    data: tempArray.filter(//some change function)
})

If you are trying to initialize your data into state, you can do it like this:

import JsonData from "./myJsonData"
constructor(props) {
super(props);
this.searchBarRef = React.createRef();
this.state = {
  data: JsonData
};

}

Hope this solves your issue. If I couldn't explain clearly please say, so I can try to give a better answer to your problem.

As Felix Kling said in commentary, you want an Array of Object so you need to have a structure like that :

this.setState({
  data: [
    ...this.state.data,
    { title, photo, summ }
  ];
});

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