首页 > 解决方案 > 数据正在插入对象中,但未在反应中更新列表组

问题描述

我正在将输入数据插入到对象中,并且该对象在列表元素中循环,而我将新项目插入到对象中,但列表的循环

请帮助我提前谢谢

并在此功能完成后帮助我重置输入字段

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;

标签: javascriptreactjs

解决方案


你需要放入todos状态,即

constructor(props) {
  super(props);
  this.state = {todos: /*...*/}
}

并在insertData

//...
this.setState({...this.state, todos: [...this.state.todos, item]});

然后,默认方式shouldComponentUpdate将拾取状态。使其可见的稍微奇怪的方式为使用不变性和/或状态管理框架提供了一个案例;就其本身而言,您应该能够继续前进


推荐阅读