You need to enable JavaScript to run this app. React存储在state中的数组元素删除时误删非目标元素问题求解
优惠活动
大模型
产品
解决方案
定价
更多

React存储在state中的数组元素删除时误删非目标元素问题求解

React列表删除行渲染异常问题

我为这个问题困扰了很久,甚至都可能看不出其中显而易见的错误了。
该App包含多个行,每行有不同尺寸的单元格,新增行、新增单元格功能均正常,但删除行功能异常:点击删除第0行的按钮,第2行消失;点击删除第1行的按钮,还是第2行消失。通过React dev tools查看发现,底层state中确实删除了正确的目标行,选中的也是要删除的目标行,但无论如何渲染结果都不符合预期,比如我点击删除第0行,应该是第0行消失。
如果从序号最大的行开始往下删除功能正常,但从第0行开始删的话,第0行无法被删除。

原排查方向代码

我一直把排查重点放在App类的deleteRowButtonHandler方法上,代码如下:

deleteRowButtonHandler( e )
        {
            const targetRow = parseInt( e.target.id ) 
console.log( "TARGETING: ", targetRow )

            const currentRows = this.state.rows

            let newArray = []
            currentRows.forEach( entry =>
            {
                console.log( "Looking at ", entry.id )
                if( entry.id == targetRow )
                    console.log( 'skipping entry with id', entry.id )
                else
                    newArray.push( entry )
            })

            console.log( newArray )
            this.setState( {rows: newArray})
            //let newRows = currentRows.filter( thisRow => {console.log( thisRow.id + ' and the target ' +  targetRow);
             //   if( thisRow.id == targetRow )
             //   {
             //       console.log( thisRow )
             //       console.log( '...is the row that we are trying to delete' )
            //    }

            //    return thisRow.id !== targetRow} 
            //) 
            //this.setState( {rows: newArray}, console.log( "NEW STATE:", this.state ))
        }

我试过多种实现方式,包括filter、splice,简写、多步实现等,目前这段代码写得并不理想。

最终根因(问题更新)

整体来看问题出在我作为React新手,此前不知道组件构造函数只会执行一次:我在子组件的构造函数中写了this.cells = this.props.cells,然后在render方法中调用this.cells.map( ... )渲染。由于构造函数仅执行一次,state更新后this.cells永远不会更新,才导致了渲染异常。


内容的提问来源于stack exchange,提问作者Philip R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 13:39:04