JavaScript   发布时间:2022-04-16  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了javascript – React JS:如何从this.state.data中正确删除一个项目,其中数据是一组对象大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
基于通过 @L_944_0@调用检索的数据数组,我有一个组件生成一行数据行(< tr>等).一切都适用于编辑和添加数据,但是我无法确定如何使数组的不同副本(包含对象的不同副本 – 通过val,而不是ref),以便当我删除指定的行数据,适用的行从表中删除.

目前,由于包含的对象是ref,即使我做了一个数组的副本,我的表也删除了最后一行(即使在AJAX调用中行索引和数据都被正确引用和删除).

handleRowdelete: function(rowIdX) {
     // Correct row 
     var row = this.state.data[rowIdx];

     // This makes a new array,but the contained objects are still by ref
     var rows = this.state.data.slice();

     // This contains the proper row that will be deleted. If this array is set to data,the table is updated to reflect just the one row - as expected.
     var throwout = rows.splice(rowIdx,1);
     console.log(throwout);

     // Whether I set via the React.addons: 
     var newState = React.addons.update(this.state,{
         data: { $set: rows }
     });
     this.setState(newStatE);

     // Or just set the state again via this.setState(...)
     //this.setState({data: rows,add: falsE});

     // It always just removes the last row in the component render
     // Even though the proper row gets deleted following in AJAX call
     $.ajax({
     ...
},...

我理解React不能做出正确的差异,所以渲染没有被触发,所以你能告诉我应该如何处理?

updatE.相关循环:

var Grid = React.createClass({
    propTypes: {
        data: React.PropTypes.array.isrequired,onCellChange: React.PropTypes.func.isrequired,onRowCommit: React.PropTypes.func.isrequired
    },render: function() {
        var rows = this.props.data.map(function(rowData,indeX) {
            return <Row key={index} data={rowData} onCellChange={this.props.onCellChange.bind(null,indeX)} onRowCommit={this.props.onRowCommit.bind(null,indeX)} onRowdelete={this.props.onRowdelete.bind(null,indeX)} />;
        },this);

        return (
            <Table Striped bordered hover responsive>
              <thead>
              <tr>
                <th className="col-sm-4">Order Sub@R_561_10586@l (up to)</th>
                <th className="col-sm-2">Canada</th>
                <th className="col-sm-2">US</th>
                <th className="col-sm-2">International</th>
                <th className="col-sm-1"></th>
              </tr>
              </thead>
              <tbody>
                    {rows}
              </tbody>
            </Table>  
        );
    }
});

解决方法

您需要确保键值在对象实例的生命周期中保持不变.正如你已经编码的那样,键值基于Array中的索引.如果从Array中删除一个元素,索引将被更新,密钥也将被更新.而且,因此,对象的键将会更改,而React将会显示为不能正确应用新的数组更改(即使底层数组已更改).

您需要使用每个对象实例中的唯一值作为关键字,或者人为地创建一个(仅为每个对象分配唯一的数字).

大佬总结

以上是大佬教程为你收集整理的javascript – React JS:如何从this.state.data中正确删除一个项目,其中数据是一组对象全部内容,希望文章能够帮你解决javascript – React JS:如何从this.state.data中正确删除一个项目,其中数据是一组对象所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。