简体   繁体   中英

How do I clear/reset an array inside state in React (JSX)

I am trying to make a simple page with React and JSX that will generate a couple of input fields which can be erased by clicking a button.

I am currently storing an empty array within the Page's state, which gets updated by the addItems function.

For some reason, I am not able to clear the array with my clear function. I understand that setState is asynchronous, but my array never gets updated and never disappears.

"use strict";

function Node(props) {
    return(<div>
        <input type="text" placeholder="input here"></input>
    </div>);
}

class Page extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            arr: [],
            thresh: 5,
            del: "Delete",
        };
        this.addItem = this.addItem.bind(this);
        this.clear = this.clear.bind(this);
    }

    addItem = (index, array) => {
        if (index == this.state.thresh) {
            this.setState((state, props) => ({
                arr: array,
            }));
            return;
        }
        index++;
        array.push(<Node key={index} />);
        this.addItem(index, array);
    };

    clear = newArr => {
        this.setState({
            arr: newArr,
        }, () => { console.log(this.state.arr) });
    };

    render() {
        return(<div id="wrapper onClick={() => {this.addItem(0,[])}}>
        <div id="fields">
        {this.state.arr}
        </div>
        <button onClick={() => {this.clear([])}}>{this.state.del}</button>
        </div>
    }
}
ReactDOM.render(<Page />, document.getElementById("root"));

I am expecting that when I hit the delete button the array will be overwritten with an empty array but this does not happen. What could I be doing wrong?

clear function looks alright, altho when i tried to run your code, it popped up multiple errors and a typo. Also addItem method looks weird to me... you are not pushing nodes into state.arr instead your are pushing it into empty array all the time.

here i tried to clean up code a bit, and even though functionality might not be what you want to have, it proves the concept that cleanup is the first thing you need to do :)

in snippet below clear function works fine and it's not modified.


function Node(props) {
    return(<div>
        <input type="text" placeholder="input here"></input>
    </div>);
}

class Page extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            arr: [],
            thresh: 5,
            del: "Delete",
        };
        this.addItem = this.addItem.bind(this);
        this.clear = this.clear.bind(this);
    }

    addItem(index, array) {

        var newArr = JSON.parse(JSON.stringify(this.state.arr))
        newArr.push(<Node />)
            this.setState({
              arr: newArr
            });
    }

    clear(newArr) {
        this.setState({
            arr: newArr,
        }, () => { console.log(this.state.arr) });
    }

    render() {
        return(<div>
        <div id="wrapper" onClick={() => {this.addItem(0,[1])}}>asdasd</div>
          <div id="fields"> {this.state.arr} </div>
          <button onClick={() => {this.clear([])}}>{this.state.del}</button>
        </div>)
    }


}
ReactDOM.render(<Page />, document.getElementById("root"));

Try building / adding your logic on top of code here and it will work.

Your clear method should look like this:

clear = () => {
        this.setState({
            arr: [],
        });
    };

your click handler in button :

<button onClick={this.clear}>{this.state.del}</button>

and if you use arrow functions you don't have to bind them in constructor, you can remove bind's

`

clear = () => {
        this.setState({
            arr: [],
        }, () => { console.log(this.state.arr) });
        setTimeout(() => { console.log("o/p", this.state.arr); }, 3000);
    };

` It will work try to put timer function. it works Acyncronasly.

I'm noticing quite a few problems here but one thing i see is your delete button is wrapped in the container that adds. so every time you click delete, it also will add to the array.

on another note though, this code doesn't seem functional. The way its written looks like it will never add anything to the state array so i'm not sure how you are seeing anything other than an empty array.

I believe you're trying to accomplish something like this:

function Node(props) {
    return (<div>
        <input type="text" placeholder="input here"></input>
    </div>);
}

export default class ClearTest extends React.Component<any, any> {
    constructor(props: any) {
        super(props);
        this.state = {
            arr: [<Node key={1} />],
            thresh: 5
        };
    }

    addItem = () => {
        const { arr, thresh } = this.state;
        if (arr.length < thresh)
        this.setState({ arr: [...(arr), <Node key={arr.length + 1} />] })
    };

    clear = () => {
        this.setState({ arr: [] }, () => { console.log(this.state.arr) });
    };

    public render() {
        return (
            <div id="wrapper">
                <div id="fields">
                    {this.state.arr}
                </div>
                <button onClick={this.clear}>Delete</button>
                <button onClick={this.addItem}>Add</button>
            </div>
        );
    }
}

this will move the add to a button and allow up to 5 inputs to be added. Clicking delete will remove them all.

You can try to reset it using a custom reset function:

import React, { Component } from 'react';

const getDefaultState = () => ({
  myArray: [],
});

class MyComponent extends Component {
  constructor(props) {
    super(props);
    this.state = { ...getDefaultState() };
  }

  componentDidMount() {
    this.setState({ myArray: [1, 2, 3] })
  }

  resetState = () => {
    this.setState({ ...getDefaultState() });
  };

  render() {
    return (
      <div onClick={this.resetState}>
        {JSON.stringify(this.state.myArray)}
      </div>
    );
  }
}

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