【问题标题】:state is not updating in react [duplicate]状态没有在反应中更新[重复]
【发布时间】:2017-09-05 07:43:11
【问题描述】:

我尝试在新员工数据输入时更新状态。但是推送功能没有将新员工数据插入状态。在 addpar 函数中我设置了 console.log 并显示数据存在但它未能将其推向状态

 // this class will hold the table and the form 

class EmpContainer extends React.Component{
    constructor(props) {
      super(props);
    // the state will have the following data by default 
      this.state = {participants : [
                    {   id: '1',
                        name: 'Dani', 
                        email: 'dani@hotmail.com',
                        phone: '0443322118'
                    },
                    {   id: '2',
                        name: 'Dani', 
                        email: 'dani@hotmail.com',
                        phone: '0443322118'
                    }
                ]};
    }

    // this supposed to add the new employed data to the state
    addPar (emp){
    console.log(emp); // this shows the new employee data 

    this.state.participants.push(emp);
       this.setState({
         participants: this.state.participants
       });}
render() {
        return (
            <div>
             <AddNewParticipant addNew={this.addPar}/>
            </div>
        );}
}

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    我现在已将其复制到an answer to the dupetarget 并将其设为 CW;这是为您的代码量身定制的版本。


    两个问题:

    1. 您不能直接在 React 中改变状态对象。相反,通过 setState 提供一个 new 数组,其中包含新条目。
    2. 根据现有状态更新状态时,请使用setState的函数回调版本,而不是接受对象的版本,因为状态更新是异步的,可能会被合并。

    React 文档中的更多内容:Using State Correctly(“不要直接修改状态”和“状态更新可能是异步的”部分)。

    所以:

    addPar(emp) {
        this.setState(function(state) {
            return {
                participants: [...state.participants, emp]
            }
        });
    }
    

    或者用一个简洁的箭头(我们需要在主体表达式周围加上(),因为我们使用了一个对象初始化器,否则{ 似乎会启动一个冗长的函数主体):

    addPar(emp) {
        this.setState(state => ({
            participants: [...state.participants, emp]
        }));
    }
    

    【讨论】:

    • using-state-correctly +1
    猜你喜欢
    • 2020-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    • 2021-03-18
    • 2021-11-02
    • 2020-12-01
    相关资源
    最近更新 更多