如何更新reactjs中的对象数组

时间:2017-03-31 08:16:50

标签: reactjs

我无法弄清楚如何正确更改我的应用中的状态。例如,我想要改变' modalStatus'特定帖子的关键是真的,我应该在showModal函数中写什么?我有以下数据结构:

class App extends React.Component {
constructor() {
super();
this.state = {
  posts: [
    {
      'author': 'Adolf Hitler',
      'img': 'http://www.jewishvirtuallibrary.org/images/hitler1.jpg',
      'content': 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Iosif Stalin',
      'img': 'http://xn--h1aagokeh.xn--p1ai/wp-content/uploads/2016/07/46432404.jpg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Napoleon Bonapard',
      'img':'http://cdn.history.com/sites/2/2015/04/hith-6-things-you-should-know-about-napoleon-E.jpeg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    },
    {
      'author': 'Vladimir Putin',
      'img':'http://realnienovosti.com/images/148795554214.jpg',
      'content':'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam deleniti incidunt consectetur omnis molestiae exercitationem accusamus nostrum quia libero esse maxime aliquid ducimus, placeat rem commodi. Animi cum aut odit.',
      modalStatus: false
    }
  ]
};

负责改变状态的函数:

showModal () {
 this.setState(do something)
 }

2 个答案:

答案 0 :(得分:0)

你可以这样做:

showModal () {
  var item = this.state.posts[0];
  item.modalStatus = true;
  this.setState({});
}

之后 - React将根据新的状态对象重新渲染组件。

答案 1 :(得分:0)

像这样写,将索引传递给你要编辑其值的函数

showModal (index) {
   var posts = JSON.parse(JSON.stringify(this.state.posts));
   posts[index].modalStatus = true;
   this.setState({posts});
}

检查DOC

或者您可以使用update immutability helper

this.setState({
    posts: update(this.state.posts, {0: {modalStatus: {$set: true}}})
})