如何添加新的键值来响应js状态数组?

时间:2017-01-12 09:37:57

标签: reactjs state setstate

我想为数组nto状态添加新的键值?我告诉你我想在下面做什么。我怎样才能做到这一点? 1.在consruture方法中启动状态

`this.state = {
    files: []
}'
  1. 使用活动文件设置状态后

    this.setState({files:activeFiles})

  2. 屏幕我的状态

    { files: [ { key1: val1, key2: val2, key3: val3 }, { key1: val1, key2: val2, key3: val3 }, { key1: val1, key2: val2, key3: val3 } ] }

  3. 如何为每个文件添加新的键值? 我想要的州

    { files: [ { key1: val1, key2: val2, key3: val3, key4: val4 }, { key1: val1, key2: val2, key3: val3, key4: val4 }, { key1: val1, key2: val2, key3: val3, key4: val4 } ] }

2 个答案:

答案 0 :(得分:4)

我认为这将符合上述情况。

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

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

答案 1 :(得分:0)

您可以使用forEach并添加新值,例如

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

<强>小提琴

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>