最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Updating state array length in React - Stack Overflow

programmeradmin1浏览0评论

I created a simple react to do list. But I want to display how many items are on that list. Every time I click submit I want to update totalItems.

  1. Items - is array of list items.
  2. Total Items - at first 0 because i'am not looking to store values. Later it bees state.items.length.

My Thoughts: Using Componentdidmount() Did worked but it had many problems. First submit didn't update, first delete didn't update. There has to be a better way. But I'm out of ideas.

My Code

this.state = {
  items: [],
  totalItems: 0,
};
this.addItem = this.addItem.bind(this);
this.deleteItem = this.deleteItem.bind(this);

ponentDidMount() {
  if (this.state.items.length > 0) {
    this.setState({
      totalItems: this.state.items.length,
    })

  } else {
    this.setState({
      totalItems: 0
    })
  }

  this.forceUpdate();
}
addItem(event) {
  thisponentDidMount();
}
deleteItem(key) {
  thisponentDidMount();
}
render() {
  return ( <
    div >
    Total Items {
      this.state.totalItems
    } <
    /div>
  )
}

I created a simple react to do list. But I want to display how many items are on that list. Every time I click submit I want to update totalItems.

  1. Items - is array of list items.
  2. Total Items - at first 0 because i'am not looking to store values. Later it bees state.items.length.

My Thoughts: Using Componentdidmount() Did worked but it had many problems. First submit didn't update, first delete didn't update. There has to be a better way. But I'm out of ideas.

My Code

this.state = {
  items: [],
  totalItems: 0,
};
this.addItem = this.addItem.bind(this);
this.deleteItem = this.deleteItem.bind(this);

ponentDidMount() {
  if (this.state.items.length > 0) {
    this.setState({
      totalItems: this.state.items.length,
    })

  } else {
    this.setState({
      totalItems: 0
    })
  }

  this.forceUpdate();
}
addItem(event) {
  this.ponentDidMount();
}
deleteItem(key) {
  this.ponentDidMount();
}
render() {
  return ( <
    div >
    Total Items {
      this.state.totalItems
    } <
    /div>
  )
}

Share Improve this question edited Mar 7, 2019 at 0:09 Hemant Parashar 3,7842 gold badges17 silver badges23 bronze badges asked Mar 6, 2019 at 19:41 Arnas DičkusArnas Dičkus 6751 gold badge13 silver badges29 bronze badges 1
  • You need to understand how React works. You're calling ponentDidMount yourself which is a lifecycle method which is an anti-pattern. See this stackoverflow./questions/48187268/… – Hemant Parashar Commented Mar 6, 2019 at 19:47
Add a ment  | 

2 Answers 2

Reset to default 4

Instead of storing a separate variable for the length of the items array, you can use this.state.items.length directly in the render method.

render() {
  return <div>Total Items {this.state.items.length}</div> 
}

class App extends React.Component {
  state = {
    items: []
  };

  addItem = () => {
    this.setState(({ items }) => ({ items: [...items, Math.random()] }));
  };

  render() {
    return (
      <div>
        <div>Total Items {this.state.items.length}</div>
        <button onClick={this.addItem}>Add item</button>
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

var dataa = {
  name : "amine",
  op : []
}


class App2 extends React.Component {

  constructor(props) {
    super(props);
    this.state = {

      myarray : dataa.op
     
   }
  }



  increment  = (e) => {


    e.preventDefault();
    const option = e.target.elements.namee.value; 
    console.log(option)
    this.state.myarray.push(option)
    this.setState({myarray : this.state.myarray })
    console.log(this.state.myarray)
  
  }

  
render() {
  return(


    <div>
      <p>{this.state.myarray.length}</p>

      <form onSubmit= {this.increment}>

          <input type="text" name  ="namee" />
          <button  type="submit">add option</button>


      </form>

    </div>

);


  }
 }

export default App2;
发布评论

评论列表(0)

  1. 暂无评论