简体   繁体   中英

Uncaught TypeError: data.push is not a function. How can I get around this push error?

First I have this addNameId method

addNameId(event) {
  event.preventDefault();
  var data = this.props.data;
  data.push({name:this.props.name, id: this.props.id})
  this.props.setData(data);

}

Everything is good until I call removeData

removeData(key) {
  console.log(key);
  const data = {...this.state.data};
  delete data[key];
  this.setState({ data });
}

Once I call removeData I can no longer add anything to data.

this is where I call them

  renderData(key){
          if (!this.props.data[key]) return null;
          const user = this.props.data[key] || {};
          console.log(user.name);
          console.log(user.id);
          return(
            <div key={key}>
                <li>  <strong> Name: </strong>  {user.name},
                <strong>  ID: </strong> {user.id} </li>
                <button onClick={() => this.props.removeData(key)}> Remove </button>
            </div>
          )
        }

What can I replace data.push({name:this.props.name, id: this.props.id}) with?

Edit:

My constructor

  constructor() {
    super();
    this.setId = this.setId.bind(this);
    this.setName = this.setName.bind(this);
    this.setData = this.setData.bind(this);
    this.removeData = this.removeData.bind(this);

    this.state = {
      name: '',
      data: [],
      id: '',
    };
  }

There a re few things that you need to correct.

  1. In the addNameId function you specify var data = this.props.data; , however only set a reference of data to the prop and so you are mutating the props directly

Change to

addNameId(event) {
  event.preventDefault();
  var data = [..this.props.data];
  data.push({name:this.props.name, id: this.props.id})
  this.props.setData(data);

}
  1. You are creating a new oobject from this.state.data in removeData , by const data = {...this.state.data}; . What it does is that it destructures the contents within this.state.data and creates an object instead. Since this.state.data was an array, you should have done const data = [...this.state.data];

  2. delete removes a key form an object and when you use an array, you can use splice to remove object at an index equal to key like data.splice(key, 1)

Change the function to

removeData(key) {
  console.log(key);
  const data = [...this.state.data];
  data.splice(key, 1);
  this.setState({ data });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM