我正在开发一个使用 React 和 ReFlux 的项目。目前我只有一家 ReFlux 商店:SubscriptionStore.js
. 它包含有关用户订阅的简单详细信息,包括嵌套对象数组,其中包含附加到其订阅的每个“标题”的详细信息。
以下是背后数据的简单细分SubscriptionStore.js
:
{
hasThisSubcription: 0
hasThatSubscription: 1
nextPeriodStart: "2015-10-12"
nextYearStartDate: "2016-09-12"
accountTitles: [{
id: "1"
title: "The Name"
createdDate: "2015-09-12 16:17:08"
}, {
id: "2"
title: "Another Name"
createdDate: "2015-09-12 16:17:08"
}, {
id: "3"
title: "Yet Another Name"
createdDate: "2015-09-12 16:17:08"
}]
}
我有一个 React 组件,它允许用户更新现有标题的名称、添加新标题或删除标题。添加和重命名进展顺利,但删除行为不端,我敢肯定这是因为我还没有完全掌握 React/ReFlux。
以下是该主要组件的相关代码:
var React = require('react')
var Reflux = require('reflux')
var SubscriptionActions = require('../../stores/SubscriptionActions.js')
var SubscriptionStore = require('../../stores/SubscriptionStore.js')
module.exports = React.createClass({
mixins: [
Reflux.connect(SubscriptionStore, 'subscriptions')
],
/**
* Add new title
* @param {number} id The Title ID
*/
addTitle() {
SubscriptionActions.addNewTitle()
},
/**
* Remove Title from state using on ID
* @param {number} id The Title ID
*/
removeTitle(id) {
SubscriptionActions.removeNewTitle(id)
},
/**
* Update Title title using ID
* @param {number} id The Title ID
* @param {string} value The new title
*/
saveTitle(id, value) {
SubscriptionActions.updateNewTitle(id, value)
},
render() {
// Check for Title subscriptions and create an editable field for each
var theTitles = []
for (var i = 0; i < this.state.subscriptions.accountTitles.length; i++) {
theTitles.push(
<EditableCapsule
key = {i}
ref = {'title' + i}
removable = {i === 0 ? false : true}
labelValue = ''
clickToRemove = {this.removeTitle.bind(this, i)}
primaryAction = {this.saveTitle.bind(this, i)}
/>
)
}
return (
<div>
<ScrollArea ref='scrollArea'>
{theTitles}
</ScrollArea>
</div>
)
}
})
以及来自的相关代码SubscriptionStore.js
:
removeTitle(id) {
this.subscriptions.accountTitles = _.without(this.subscriptions.accountTitles, _.findWhere(this.subscriptions.accountTitles, { id: id }));
this.trigger(this.subscriptions)
}
问题
无论我单击要删除哪个标题,它始终是最后一个被删除的标题。如果我吐出this.subscriptions.accountTitles
内容的前后,则表明确实从数据中删除了正确的对象,但 React 正在渲染元素,就好像它总是被删除的最后一个项目一样。
知道会发生什么吗?