首页 > 解决方案 > 在 React 中更新对象数组值的最佳方法是什么

问题描述

我的反应state

//...
this.state = {
    mylist: [
        {
            "id": 0,
            "trueorfalse": false
        },
        {
            "id": 1,
            "trueorfalse": false
        }
    ]
}
//...

我正在尝试trueorfalse根据id

这是我到目前为止所做但没有奏效的方法:

var idnum = e.target.id.toString().split("_")[1] //getting the id via an element id (0 or 1 in this case)
var TorF = true
if (type === 1) {
    this.setState({
        mylist: this.state.mylist.map(el => (el.id === idnum ? Object.assign({}, el, { TorF }) : el))
    })
}

我真的想让它变得动态,所以它trueorfase会与现在相反:

var idnum = e.target.id.toString().split("_")[1] //getting the id via an element id (0 or 1 in this case)
if (type === 1) {
    this.setState({
        mylist: this.state.mylist.map(el => (el.id === idnum ? Object.assign({}, el, { /* if already true set to false or vice versa */ }) : el))
    })
}

如何更新我的代码以具有第二个示例中显示的动态性(如果可能),否则第一个示例会很好

标签: arraysreactjsobject

解决方案


另一种解决方案使用map

编辑 withered-field-889f8

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      mylist: [
        {
          id: 0,
          trueorfalse: false
        },
        {
          id: 1,
          trueorfalse: true
        }
      ]
    };
  }
  toggleBoolean = () => {
    const ID = Number(this.state.selectedID);
    this.setState(prevState => ({
      mylist: prevState.mylist.map(item => {
        if (item.id === ID) {
          return { ...item, trueorfalse: !item.trueorfalse };
        } else {
          return item;
        }
      })
    }));
  };
  render() {
    return (
      <div className="App">
        <p>{`State values: ${JSON.stringify(this.state.mylist)}`}</p>
        <button onClick={this.toggleBoolean}>Change true/false values</button>
        <label>Insert ID:</label>
        <input
          type="number"
          onChange={event => this.setState({ selectedID: event.target.value })}
        />
      </div>
    );
  }
}

推荐阅读