Ted*_*Ted 14 javascript reactjs
我有一个组件,它<tr>
根据通过AJAX调用检索的数据数组生成一个包含数据行(等)的表.一切都适用于编辑和添加数据,但我无法确定如何制作数组的不同副本(包含所包含对象的不同副本 - 由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({
...
},
...
Run Code Online (Sandbox Code Playgroud)
我理解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 Subtotal (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>
);
}
});
Run Code Online (Sandbox Code Playgroud)
Wir*_*rie 14
您需要确保该key
值在对象实例的生命周期内保持不变.当你拥有了它的编码,该key
值是基于index
到Array
.如果从中删除一个元素Array
,则会更新索引,因此键也会更新.并且,因此,对象key
将发生变化,并且React似乎无法正确应用新的数组更改(即使基础数组已更改).
您需要使用每个对象实例中的唯一值作为key
或人工创建一个(只需为每个对象分配一个唯一的数字).
归档时间: |
|
查看次数: |
13319 次 |
最近记录: |