[英]Updating state array length in React
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.
每次单击提交时,我都想更新 totalItems。
My Thoughts: Using Componentdidmount() Did worked but it had many problems.我的想法:使用 Componentdidmount() 确实有效,但有很多问题。 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); 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> ) }
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.您可以直接在渲染方法中使用
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.