簡體   English   中英

在 React 中更新狀態數組長度

[英]Updating state array length in React

我創建了一個簡單的反應待辦事項列表。 但我想顯示該列表中有多少項目。 每次單擊提交時,我都想更新 totalItems。

  1. Items - 是列表項的數組。
  2. Total Items - 起初為 0,因為我不想存儲值。 后來它變成 state.items.length。

我的想法:使用 Componentdidmount() 確實有效,但有很多問題。 第一次提交沒有更新,第一次刪除沒有更新。 一定有更好的方法。 但我沒有想法。

我的代碼

 this.state = { items: [], totalItems: 0, }; this.addItem = this.addItem.bind(this); this.deleteItem = this.deleteItem.bind(this); componentDidMount() { if (this.state.items.length > 0) { this.setState({ totalItems: this.state.items.length, }) } else { this.setState({ totalItems: 0 }) } this.forceUpdate(); } addItem(event) { this.componentDidMount(); } deleteItem(key) { this.componentDidMount(); } render() { return ( < div > Total Items { this.state.totalItems } < /div> ) }

您可以直接在渲染方法中使用this.state.items.length ,而不是為items數組的長度存儲單獨的變量。

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.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM