替换setState中垂直索引处的数组对象

时间:2019-04-11 13:01:59

标签: reactjs

我有一个更新按钮,它为我提供了更新后的对象,并且有一个索引,我想用该对象替换数组:

updateVal = () => {
  console.log("this.state::", this.state);
  let alleditvals = {
    username: this.state.uname_edit,
    password: this.state.pass_edit,
    address: this.state.address_edit
  };
  console.log("w::", this.state.add_data[this.state.count_edit]);
  console.log("alleditvals::", alleditvals);
  console.log("this.state.add_data[1]", this.state.add_data[1]);

  this.state.add_data.map((a, i) => {
    console.log("i::", i);
    console.log("a::", a);

    if (this.state.count_edit == i) {
      console.log(this.state.add_data[i]);
    }
  });
}

状态如下:

this.state = {
  uname: "",
  pass: "",
  address: "",
  salary: "",

  add_data: [],

  edit_obj: {},
  edit_showui: false,

  uname_edit: "",
  pass_edit: "",
  address_edit: "",
  count_edit: null,
  changed_after_edit: {},

  errorfields: {
    uname_err: "",
    pass_err: "",
    address_err: "",
    salary_err: "",
    valid_user: false,
    valid_pass: false,
    valid_address: false,
    valid_salary: false
  }
};

所以我的数组是add_data,我想用索引alleditvals上的this.state.count_edit替换。我还检查了map函数,如果当前计数的索引与add_data索引匹配,请替换它,但不知道如何替换它。

if(this.state.count_edit == i){
  console.log(this.state.add_data[i])
}

2 个答案:

答案 0 :(得分:0)

您可以使用setState方法更新组件状态,并在map数组上使用数组方法add_data,并用{替换索引count_edit处的元素{1}}个对象。

alleditvals

答案 1 :(得分:0)

感谢setState,您可以轻松更新状态。

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      allData: [],
      index: 0
    }
  }

  componentWillMount()
  {
    this.state.allData.push({ name1: "Test1", name2: "Test2"}); 
  }

  push1 = () =>
  {
    this.setState({
      index: 1
    })
  }

  push2 = () =>
  {
    this.setState({
      index: 2
    })
  }

  render() {
    const list = this.state.allData.map((value, index) => {                                             
      return (
        <div>
        { this.state.index === 1? value.name1 : value.name2 }
        </div>
      )
    })
    return (
      <div>
      <button onClick={this.push1}>Push 1</button><br/><br/>
      <button onClick={this.push2}>Push 2</button><br/><br/>
      <div>
        {list}
      </div>
      </div>
      );
    }
  }

在此示例中,我按Push2 = Test2显示。如果按Push1,将出现Test1。

enter image description here