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

IT技术 reactjs state setstate
2021-05-15 00:08:54

我想将新的键值添加到数组中?我在下面告诉你我想做什么。我怎样才能做到这一点?1. 构造方法中的起始状态

`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个回答

我认为这将满足上述情况。

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

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

您可以使用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>