How to add a new key value to react js state array?

泄露秘密 提交于 2019-12-04 08:46:00

I think This will meet the above scenario.

const newFile = this.state.files.map((file) => {

    return {...file, key4: val4};
});
this.setState({files: newFile });

You can make use of forEach and add the new value like

var newState = [...this.state.files];
newState.forEach(function(file) {
  file.key4 = "val4"
})
this.setState({files: newState}, function() {
  console.log(this.state.files);
})

Fiddle

class App extends React.Component {
  constructor() {
    super();
    this.state = {
        files: 
        [
            {
                key1: "val1",
                key2: "val2",
                key3: "val3"
            },
            {
                key1: "val1",
                key2: "val2",
                key3: "val3"
            },
            {
                key1: "val1",
                key2: "val2",
                key3: "val3"
            }
        ]
    }
  }
  componentDidMount() {
    console.log(this.state.files) ;
    
    var newState = [...this.state.files];
    newState.forEach(function(file) {
      file.key4 = "val4"
    })
    this.setState({files: newState}, function() {
      console.log(this.state.files);
    })
  }
  render() {
    return <div>Hello</div>
  }
}

ReactDOM.render(<App/>, document.getElementById('app'));
   
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!