我正在尝试创建一个表单来提交票证。交易是,我有这些票证的视图,还有一个按钮可以在两个过滤器之间进行选择-用户拥有的票证,或者所有需要处理的票证。但是,当我尝试使用setState乐观地将票证添加到当前TicketList时,新票证被添加了TWICE-它在列表的顶部和底部。我有点困惑如何发生。这是我的票务提交功能:
handleTicketSubmit(ticket) {
const tickets = this.state.data;
// Optimistically set an id on the new ticket. It will be replaced by an
// id generated by the server. In a production application you would likely
// use a more robust system for ID generation.
var assUser = ticket.AssignedTo[0];
var newTicket = tickets[0];
newTicket.id = tickets.length + 1;
newTicket.userOwnerId = assUser.id;
newTicket.summary = ticket.Summary;
newTicket.description = ticket.Description;
//alert(assUser.id);
//alert(JSON.stringify(newTicket));
//ticket.id = tickets.length + 1;
//ticket.userOwnerId = assUser.id;
//alert("Before: " + JSON.stringify(tickets.length));
const newTickets = tickets.concat([newTicket]);
//alert("After: " + JSON.stringify(newTickets.length));
alert("Before: " + this.state.selectedData.length);
if (assUser.id == this.userState.data.id) {
var myTix = this.state.data.filter(x => x.userOwnerId == newTicket.userOwnerId);
alert(JSON.stringify(myTix));
if (myTix.length == this.state.selectedData.length) {
this.setState({ selectedData: newTickets });
}
}
else {
this.setState({ selectedData: newTickets });
}
//this.setState({ data: newTickets });
//alert(JSON.stringify(ticket));
const data = new FormData();
data.append('Summary', ticket.Summary);
data.append('Description', ticket.Description);
data.append('AssignedTo', assUser.id);
const xhr = new XMLHttpRequest();
xhr.open('post', this.props.submitUrl, true);
xhr.onload = () => this.loadTicketsFromServer();
xhr.send(data);
}
selectedData是一个数组,可以根据用户选择的过滤器选项(他/她自己的票证或所有票证)进行更改。这是JSX的props构造函数:
class Queue extends React.Component {
constructor(props) {
super(props);
this.state = { data: this.props.initialData, closedData: this.props.closedData, selectedData: this.props.initialData, matchedUserNames: [] };
this.handleTicketSubmit = this.handleTicketSubmit.bind(this);
this.toJavaScriptDate = this.toJavaScriptDate.bind(this);
this.userState = { data: this.props.userData };
this.usersCollection = { data: this.props.userDB };
this.getUsername = this.getUsername.bind(this);
this.serverMsg = { data: this.props.serverMsg };
this.srvMsgRst = { data: this.props.srvMsgRst };
this.showAllTickets = this.showAllTickets.bind(this);
this.showMyTickets = this.showMyTickets.bind(this);
this.checkServerMessage = this.checkServerMessage.bind(this);
this.showAssignModal = this.showAssignModal.bind(this);
this.filterUsers = this.filterUsers.bind(this);
this.handleUserAssign = this.handleUserAssign.bind(this);
this.selectedCheck = this.selectedCheck.bind(this);
}
万一有人好奇,这是在Queue组件中呈现的ticketList组件:
<TicketList data={this.state.selectedData} getTicket={this.props.navUrl} renderDate={this.toJavaScriptDate} checkUser={this.getUsername} />
有人会知道发生了什么吗?当我再次尝试更新selectedData的状态时,它会同时添加到selectedData的开始和结尾,而当我不调用它时,什么也没发生。当我在更改selectedData的状态后尝试通过调用警报进行调试时,由于某种原因,其长度似乎与更改前的长度相同。