【问题标题】:Adding array item at specific index - React Redux在特定索引处添加数组项 - React Redux
【发布时间】:2020-03-20 13:46:31
【问题描述】:

减速机:

const initState = ['item 1', 'item 2', 'item 3', 'item 4'];

const { text, afterIndex } = action;
switch (action.type) {
  case ADD_NOTE:
    return [
      ...state.slice(0, afterIndex + 1),
      text,
      ...state.slice(afterIndex + 1)
    ];
  default:
    return state;
}

组件,我们在其中添加新项目:

const enhance = connect(({ items }) => ({ items }), { addItem });

class ItemsList extends React.Component {
  renderItem = item => <div>{item}</div>;

  renderAddButton = (index = 0) => (
    <button
      data-index={index}
      onClick={this.onAddButtonClick}
    >
      Add item
    </button>
  );

  onAddButtonClick = e => {
    const text = window.prompt('Item text:');
    if (text) {
      this.props.addItem(text, e.target.dataset.index);
    }
  };

  render() {
    if (!this.props.items.length) {
      return this.renderAddButton();
    }
    return (
      <ul>
        {this.props.items.map((item, index) => {
          return (
            <li key={index}>
              {this.renderItem(item)}
              {this.renderAddButton(index)}
            </li>
          );
        })}
      </ul>
    );
  }
}

初始状态有 4 个项目,我通过组件中的map() 渲染它们,然后在每个项目下方有一个按钮可以在实际项目之后添加项目,但是只有第一个按钮(将项目添加到数组中)放置一个商品顺序正确。

如果我在第 2、3、4 个项目上单击“添加按钮”,它会在数组的末尾添加一个新项目,而不是在单击的项目之后。

我的案例的视觉表现:

1) 如果我点击第一个“添加项目”按钮,那么我的数组将是:['Item 1', 'my freshly added item', 'Item 2', 'Item 3', 'Item 4']

2) 如果我点击第二、第三、第四个“添加项目”按钮,那么我的数组将是:['Item 1', 'Item 2', 'Item 3', 'Item 4', 'my freshly added item'],添加到数组末尾的项目,认为应该在第二、第三和第四之后项目。

【问题讨论】:

  • splice() 确实改变了一个数组,这是 redux 的反模式。
  • 你可以splice()你的状态的浅拷贝,这不是反模式

标签: javascript reactjs


【解决方案1】:

原来是dataset 属性给了我一个索引为string,因此在reducer 中它被称为'1' + 1。

解决方案:

const index = parseInt(afterindex, 10);

【讨论】:

    猜你喜欢
    • 2016-02-16
    • 2018-03-21
    • 2018-05-16
    • 1970-01-01
    • 2016-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2011-07-05
    相关资源
    最近更新 更多