javascript - 数据正在插入对象中,但未在反应中更新列表组
问题描述
我正在将输入数据插入到对象中,并且该对象在列表元素中循环,而我将新项目插入到对象中,但列表的循环
请帮助我提前谢谢
并在此功能完成后帮助我重置输入字段
import React,{Component} from 'react';
class Home extends Component{
todos = [
{value:"hahaha", id:"01"},
{value:"duygud", id:"02"},
{value:"oisdpo", id:"03"}
]
insertData(){
let msg=document.getElementById('item').value;
let item={value:msg}
this.todos.push(item);
this.setState(this.state);
console.log(this.todos);
}
sample(msg){
alert(msg)
}
render(){
return(
<div><br /><br />
<div class="container col-4">
<input type="text" id="item" class="form-group col-12 in" name="item" onKeyPress={(event) => {if (event.key === "Enter") {this.insertData()}}} />
<ul class="list-group">
{ this.todos.map(todo => <li class="list-group-item li">{todo.value} <i class="far icon text-danger fa-times-circle float-right" onClick={()=>this.sample('hello data')}></i></li> )}
</ul>
</div>
</div>
);
}
}
export default Home;
解决方案
你需要放入todos
状态,即
constructor(props) {
super(props);
this.state = {todos: /*...*/}
}
并在insertData
:
//...
this.setState({...this.state, todos: [...this.state.todos, item]});
然后,默认方式shouldComponentUpdate
将拾取状态。使其可见的稍微奇怪的方式为使用不变性和/或状态管理框架提供了一个案例;就其本身而言,您应该能够继续前进
推荐阅读
- lotus-notes - Lotus Sametime Embedded - 窗口格式
- python - 将部分函数调用保存在 json 文件中
- python - 我是在 dataset.repeat() dataset.batch() 和 dataset.prefetch() 之前还是之后缓存数据集?
- java - 保存无线电组 onSavedInstance
- django - /course/expression-regular-django/ 'ContactCourses' 对象的 AttributeError 没有属性 'name'
- ruby-on-rails - Ice Cube 如何为每次发生设置持续时间
- python - 如何更改帧分辨率opencv python
- android - CoreComponentFactory没有找到类“android.support.v4.app.CoreComponentFactory”
- java - isDigit 方法中的 Character.isDigit 参数和行不可用错误(澄清)
- encryption - 使用 PBKDF2 在 Jackrabbit OAK 中存储密码哈希