我正在创建一个 Web 应用程序,它允许用户在屏幕上拖放多个片段,每个片段都包含单独的特定数据。如果用户想要在屏幕上添加更多片段,他们只需单击一个按钮,另一个片段就会出现。我使用 React DND(Drag and Drap)库来保持我的组件解耦,到目前为止效果很好。问题在于在屏幕上添加更多片段的动态功能。目前(在下面的子代码中),我正在获取旧状态对象,执行浅拷贝,并将新创建的对象与预先存在的状态对象合并,并在完成时更新状态。但是,每次我执行此操作时,一切正常(屏幕上生成新片段),直到我移动一个新片段并出现以下错误:
在现有状态转换期间无法更新(例如在 内
render
)。渲染方法应该是 props 和 state 的纯函数。
我怎样才能摆脱这个错误,并更新状态对象。
注意:按钮(在下面的屏幕截图中)显示 State 对象中对象数量的当前计数。所以下面我在状态中添加了 7 个对象
import React, { Component, PropTypes } from 'react';
import Header from '../../components/Header/header';
import Footer from '../../components/Footer/footer';
import Student from '../../components/box1/box1';
import Box from '../../components/box2/box2';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
require('./home.css');
var Home = React.createClass({
getDefaultProps: function(){
return{ count: 3 }
},
getInitialState: function(){
return{ count: this.props.count }
},
add: function(){
this.setState({ count: this.state.count + 1 });
},
render() {
return (
<div id="main">
<Box count = {this.state.count}/>
<button count = {this.state.count} onClick = {this.add} > {this.state.count} </button>
</div>
);
}
});
export default DragDropContext(HTML5Backend)(Home);
孩子:
import React from 'react';
var ItemTypes = require('../box1/Constants').ItemTypes;
var DropTarget = require('react-dnd').DropTarget;
var Student = require('../box1/box1');
import update from 'react/lib/update';
require('./box2.css');
var BoxSource = {
drop: function (props, monitor, component) {
const item = monitor.getItem();
console.log(item);
const delta = monitor.getDifferenceFromInitialOffset();
const left = Math.round(item.left + delta.x);
const top = Math.round(item.top + delta.y);
const id = item.id;
component.move(id, left, top);
}
};
function collect(connect, monitor) {
return {
connectDropTarget: connect.dropTarget(),
didDrop: monitor.didDrop(),
source: monitor.getSourceClientOffset(),
item: monitor.getItem(),
drop: monitor.didDrop(),
result: monitor.getDropResult()
};
}
var box2 = React.createClass({
getInitialState: function() {
return { Students: {
'0': { top: 20, left: 80 },
'1': { top: 180, left: 20 },
'2': { top: 130, left: 20 },
}
};
},
componentWillReceiveProps: function(nextProps) {
var i = this.props.count;
console.log(this.state.Students);
var obj = update(this.state,{
Students:{
$merge:{
[i]:{
top: 10,
left:10
}
}
}
});
this.setState(obj);
},
move: function(id,left,top){
this.setState(update(this.state,{
Students:{
[id]:{
$merge:{
left:left,
top: top
}
}
}
}));
},
render:function() {
const { Students } = this.state;
var connectDropTarget = this.props.connectDropTarget;
return connectDropTarget(
<div id = "box">
{Object.keys(Students).map(key =>{
const { left, top, title } = Students[key];
return(
<Student key = {key} id = {key} left = {left}
top = {top}> </Student>
);})}
</div>
);
}
});
module.exports = DropTarget(ItemTypes.STUDENT, BoxSource, collect)(box2);