javascript 如何将键值对添加到状态对象 React

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49232538/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:29:11  来源:igfitidea点击:

How to add a key-value pair to state Object React

javascriptreactjsecmascript-6

提问by Anna Jeanine

I'm struggling with setting the state of one of my objects in React. The code which I have:

我正在努力在 React 中设置我的一个对象的状态。我拥有的代码:

export class RRHN_App extends React.Component {
   constructor(props) {
      super(props);
      this.startLoadingItems();
      this.fetchData();
      this.state = {
         items: [],
         itemStatus : [],
         selectedItem: null,
         prefsDialog: false,
         preferences : {
             color : "brown",
             listSize : 800
         }
      }
   }
   toggleItem(item) {
      console.log("Selected item: ", item);
      if( this.state.selectedItem &&
          item.id === this.state.selectedItem.id) {
         this.setState({selectedItem: null});
      } else {
         let ItemID= item.id;
         let newSeen = {ItemID : "seen"};
         this.setState({selectedItem: item});
         this.setState({itemStatus: newSeen});
      }
      console.log(this.state.itemStatus)
   }
   fetchData() {
        request.get("http://localhost:3000/itemStatuses")
            .end( (err,response) => {
                this.setState({itemStatus: response.body})
            })
    }
   startLoadingItems() {
        request.get("http://localhost:3000/hn/topstories")
            .end( (err,response) => {
                this.setState({items : response.body})
            })
    }
}

When printing the itemStatusI get this:

打印时itemStatus我得到这个:

{16490176: "seen", 16497964: "seen", 16514428: "read", 16542395: "read", 16566536: "read"}

When the code is executed the itemStatuslooks like this:

当代码执行时,itemStatus看起来像这样:

{ItemID: "seen"}

How can I add a key-value pair of the item.id and "seen" to the state?

如何将 item.id 和“seen”的键值对添加到状态?

回答by Markus

Additionally to the dynamic key Rajesh pointed out, also note the setStatewill shallow merge existing and new state: Try

除了 Rajesh 指出的动态键之外,还要注意setState将浅合并现有状态和新状态:尝试

this.setState({[ItemId]: 'seen'})