无法在reactjs中添加项目到列表

问题描述 投票:0回答:4

我的按钮和函数调用如下:

<td>
  <button
    id="home.js"
    type="button"
    className="btn btn-default btn-sm"
    onClick={this._onButtonClickHome}
  >
    <span className="glyphicon glyphicon-plus" />
  </button>
</td>

我的反应代码是:

constructor() {
  this.state = {
    idList: ["hi"],
    showComponentHome: false
  };
}

_onButtonClickHome(event) {
  const idhome = event.target.id;
  console.log(idhome);
  this.state.idList.push(idhome);
  console.log(this.state.idList);
  this.setState({
    showComponentHome: true
  });
}

我无法将ID“home.js”添加到列表idList中。有人可以解决问题或建议更好的方法吗?谢谢。

reactjs
4个回答
-2
投票
  1. 请将按钮代码更改为以下内容:
<td><button id="home.js" type="button" className="btn btn-default btn-sm" onClick={(event) => this._onButtonClickHome(event)}><span className="glyphicon glyphicon-plus"></span></button></td>
  1. 请自动绑定该功能,如下所示:
_onButtonClickHome = (event) => {
  // Your code
}
  1. 你不能直接推送到this.state.idList。复制一份。
const { idList } = this.state;

[这相当于const idList = this.state.idList - 技术上称为对象解构]

  1. 现在你可以推送到idList。如果你想把它放在状态上。
idList.push("idhome");

2
投票

你能尝试以下方法吗?

_onButtonClickHome(event) { 
    const idhome = event.target.id;
    const idList = Object.assign([], this.state.idList);

    idList.push(idhome);

    this.setState({idList, showComponentHome: true});
}

问题可能是您使用this.state.idList直接推送新元素,但这不是更新状态的好方法。您应该在状态中创建当前数组的副本,更新它,然后使用更新数组覆盖状态中的数组。


0
投票

遵循其文档中定义的框架规则。更多阅读:doc部分:正确使用状态。有关不可变状态的观点。


0
投票

这是工作解决方案,

import React, { Component } from "react";
class Solution extends Component {
  state = {
    idList: ["hi"],
    showComponentHome: false
  };

  _onButtonClickHome = (idhome) => {
    console.log(idhome);
    let tempArr = [...this.state.idList, idhome];
    this.setState({ idList: tempArr });
    this.setState({
      showComponentHome: true
    });
    console.log(tempArr);
  }
  render() {
    return (
      <button
        type="button"
        className="btn btn-default btn-sm"
        onClick={() => this._onButtonClickHome("home.js")}
      >
        Set State
      </button>
    );
  }
}

export default Solution;

我希望它有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.