简体   繁体   English

带有对象和数组的 ReactJS setState

[英]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 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 :正如 Felix Kling 在评论中所说,你需要一个对象数组,所以你需要有一个这样的结构:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM