使用setState更改状态下的对象数组

时间:2018-11-29 15:23:18

标签: javascript reactjs

import React, {
      Component
    } from "react";
    class App extends Component {
      state = {
        RSVP: [{
          name: ["IronMan"],
          isConfirmed: false
        }]
      };
      handleChecked = () => {
        this.setState({
          isConfirmed: true
        }););
    };
    render() {
        return ( < div > {
              this.state.RSVP && this.state.RSVP.length != 0 ? this.state.RSVP.map(({
                name,
                isConfirmed
              }) => name && name.length != 0 ? ( <
                div key = {
                  name
                } > {
                  name
                } < input type = "checkbox"
                checked = {
                  isConfirmed
                }
                onChange = {
                  this.handleChecked
                }
                /></div > ) : null) : null
            } < /div>);}}
            export default App;

1 个答案:

答案 0 :(得分:1)

您可以更改数组内对象的状态,可以使用以下源代码:

handleChange = (index) => {
  let tmp = [...this.state.RSVP];
  tmp[index] = {...tmp[index],isConfirmed: true};
  this.setState({RSVP: tmp})
}