[英]Updating state array length in React
我創建了一個簡單的反應待辦事項列表。 但我想顯示該列表中有多少項目。 每次單擊提交時,我都想更新 totalItems。
我的想法:使用 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.