import React from "react"
class Test extends React.Component {
state = {
count: 0,
list: [1, 2, 3, 4, 5],
person: { name: '张三', age: 18 }
}
//修改数据(不要直接修改状态的值,而是基于当前状态值创建新的状态值)
//添加数据
changeState = () => {
this.setState({
list: [...this.state.list, 6],
person: {
...this.state.person,
age: this.state.person.age + 1,
name: '李四'
}
}
)
}
//修改数据
//删除数据
//调用filter方法 过滤需要删除的数据
delState = () => {
this.setState({
list: this.state.list.filter((item, index) =>
index !== 2
)
})
}
render () {
return (
<div>
<ul>
{this.state.list.map((item) =>
<li key={item}>{item}</li>
)}
</ul>
<div>{this.state.person.age}{this.state.person.name}</div>
<button onClick={this.changeState}>changeState</button>
<button onClick={this.delState}>delState</button>
</div>
)
}
}
function App () {
return (
<div className="App">
<Test />
</div>
)
}
export default App