React.js - Array.unshift()不更新前端的数组

时间:2017-10-20 11:04:12

标签: javascript arrays reactjs react-dnd

我使用react-dnd实现了一个小的拖放实现。有两列,从右侧列拖动到左侧,激活特定状态项。

在下拉时,调用pushCard(),(顾名思义),将拖动的项目推送到激活状态数组,即status_data

但问题是,status_data.push(itemToPush),将新项目推送到数组的末尾。我想把项目放在数组的顶部,即数组的索引0。

status_data.unshift(itemToPush)适用于这种情况,但unshift仅更新state和后端的数组,但它不会显示更新的array在前端。相反,它会继续推动首先拖动的相同元素。

Simple description of problem in a GIF.

pushCard

pushCard(item) {
    const { status_data } = this.state.template;
    const itemToPush = {
        title : item.title || 'CUSTOM',
        type_id : item.type_id,
        color : item.color || '#000',
        type: item.type,
        require_notes: item.require_notes || false,
        require_estimate: item.require_estimate || false
    };
    status_data.unshift(itemToPush);
    this.setState(Object.assign(this.state.template, { status_data }));
}

renderActiveStatuses

renderActiveStatuses() {
    let renderedResult = '';
    if (this.state.template.status_data.length < 0) {
      renderedResult = (<p>No status active in this template.</p>);
    } else {
      renderedResult = this.state.template.status_data.map((status, i) => {
        return (
          <Status deleteStatus={this.deleteStatus} handleStatusUpdate={this.onStatusUpdate} index={i} id={status.id} moveCard={this.moveCard} statusData={status} key={status.id} />
        );
      });
    }
    return renderedResult;
}

renderActiveStatuses在组件的render函数中调用。

2 个答案:

答案 0 :(得分:1)

这个怎么样?

this.setState({template: Object.assign({}, this.state.template, { status_data })});

正如您在问题中所做的那样,您只是为您的州分配this.state.template的内容,而原始的内容永远不会更改,因此您的州将成为

state = {
    template: {status_data: ...},
    status_data: ...,
    ...
}

答案 1 :(得分:1)

status个对象(例如您在此处显示的itemToPush)没有属性id,您在key中用作Status的属性。您可以尝试key={i}(即使使用地图索引不是最好的主意)。

您可以生成(可能)唯一ID,如下所示:

const itemToPush = {
    id: Math.random().toString(36).substr(2, 16), 
    ...
}

并像以前一样使用status.id

如果在产生数百万个这样的情况下存在任何风险,那么有更好的ID生成器。

相关问题