我正在用ReactJS构建一个简单的TODO应用,需要使用jQuery Sortable对待办事项进行排序。我完成了大部分工作,但最终遇到了2个无法解决自己的问题:(
所以这是代码:
componentDidMount: function() {
this.loadDataFromServer();
var jquery_sortable_config = {handle: '#handle'};
jquery_sortable_config.stop = this.handleSort;
this.$jq = jQuery( this.refs.sortable.getDOMNode() );
this.$jq.sortable(jquery_sortable_config);
},
toInt: function(id) {
// I've got <li id={"todo_" + todo.id}></li> so I need to crop todo_
// was - todo_565
// return - 565
return parseInt(id.substring(5));
},
handleSort: function (event) {
var order = this.$jq.sortable('serialize');
// sending new order to server, here is everything OK
$.ajax ({
type: 'POST',
url: 'update_order/',
data: order
});
var reordering = this.$jq.sortable('toArray').map(this.toInt);
this.$jq.sortable('cancel'); // cancel direct DOM change, beacause React can't see it
this.handleDOMUpdate(reordering);
},
handleDOMUpdate: function(reordering) {
console.log(reordering);
// CONSOLE:
// [566, 565]
var newItems = [];
var newState = {};
this.state.data.map(function(item, i, items) {
// for testing there are just 2 elements in state and I just shuffle them
newItems[0] = items[1];
newItems[1] = items[0];
});
newState = newItems;
console.log(newState);
// CONSOLE:
// [Object, Object]
// 0: Object
// id: 566
// status: "done"
// text: "Second task"
// __proto__: Object
// 1: Object
// id: 565
// status: ""
// text: "First task"
// __proto__: Object
// length: 2
// __proto__: Array[0]
// so elements changed positions!
// trying to set new state
this.setState(newState);
// and getting error:
// Uncaught Error: Invariant Violation: Tried to merge an object, instead got [object Object],[object Object]. 10173493_255140104677950_2108691993_n.js:17078
// and futher:
// invariant 10173493_255140104677950_2108691993_n.js:17078
// mergeHelpers.checkMergeObjectArg 10173493_255140104677950_2108691993_n.js:17652
// mergeInto 10173493_255140104677950_2108691993_n.js:17749
// merge 10173493_255140104677950_2108691993_n.js:17558
// ReactCompositeComponentMixin.setState 10173493_255140104677950_2108691993_n.js:6200
// React.createClass.handleDOMUpdate custom_react.js:81
// boundMethod 10173493_255140104677950_2108691993_n.js:6644
// ... etc.
},
这是我的模型:
[
{"status": "", "text": "First task", "id": 565},
{"status": "done", "text": "Second task", "id": 566}
]
所以我有两个问题:
如何通过更改元素位置设置新的React状态?我究竟做错了什么?
您能否通过
this.state.data.map
中的逻辑帮助我。如何根据数组reordering[i]
迭代所有项目并设置其新位置? this.state.data.map(function(item, i, items) {
// logic
});
最佳答案
在运行setState调用时,您将用newItems数组newState = newItems;
覆盖newState对象,因此将函数传递给数组而不是对象。
如果使用this.setState({ data: newState });
之类的东西,则setState调用应该可以正常工作。这也应该解决第二个问题。