我创建了一个简单的待办事项列表。但我想显示该列表上有多少个项目。每次单击提交时,我要更新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>
)
}
答案 0 :(得分:4)
您无需在items
数组的长度上存储单独的变量,而可以在render方法中直接使用this.state.items.length
。
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>
答案 1 :(得分:0)
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;