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

时间:2018-03-12 10:05:50

标签: javascript reactjs ecmascript-6

我正在努力设置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})
            })
    }
}

打印itemStatus时我得到了这个:

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

执行代码时,itemStatus如下所示:

{ItemID: "seen"}

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

1 个答案:

答案 0 :(得分:4)

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

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