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

React.js - Array.unshift() not updating array on front-end

我使用 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函数中调用的。

这个呢?

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

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

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

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

您可以像这样生成一个(可能)唯一的 ID:

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

并像以前一样使用 status.id

如果您生成数百万个 ID 生成器存在任何风险,则有更好的 ID 生成器。