【问题标题】:Splice is removing the last element of array not index - ReactSplice 正在删除数组的最后一个元素而不是索引 - React
【发布时间】:2020-02-07 01:31:51
【问题描述】:

我希望每个笔记都有一个删除按钮,单击该按钮会在我的状态下从数组中删除该笔记,但 .splice 删除的是最后一个元素而不是索引。

我添加了一条警告语句来验证索引是否正确。警报显示正确的数字,但拼接删除了最后一个元素。为什么会这样?

constructor(props) {
        super(props);
        this.state = {
            Notes: ["1","2","3","4"]
        }
    }

    addNote = () => {
        var noteList = [...this.state.Notes];
        var newNote = "";
        this.setState({ Notes: noteList.concat(newNote) });
    }

    deleteNote = (index) => {
        var noteList = [...this.state.Notes];
        alert(index);
        noteList.splice(index, 1);
        this.setState({ Notes: noteList });
    }

    renderNotes(Notes) {
        return (
            <div>
                {Notes.map((Note, index) =>
                    <div class="note">
                        <div class="noteTop">
                            <button id="menu"><FontAwesomeIcon icon={faEllipsisV} /></button>
                            <button id="delete" onClick={() => this.deleteNote(index)}><FontAwesomeIcon icon={faTimes} /></button>
                        </div>
                        <textarea class="noteMain">{Note}</textarea>
                    </div>
                )}
            </div>
        );
    }

【问题讨论】:

  • 你在哪里打电话renderNotes()

标签: reactjs


【解决方案1】:

这里有几个问题。

首先,您要渲染一组您修改但未在要渲染的 div 上使用 key 的元素(请参阅:https://reactjs.org/docs/lists-and-keys.html#keys)。您的控制台应显示警告“警告:列表中的每个子项都应具有唯一的“键”道具。”。如果您向 div 添加一个键,它将按原样正确呈现您的代码。注释本身在您的示例中构成唯一键,尽管您可能希望稍后将其更改为不假定唯一注释值的东西。代码笔:https://codesandbox.io/s/eager-cray-41dv7

<div className="note" key={Note}>

第二个,但在第一次修复之后不那么重要,但稍后当你想让人们更新注释时会影响你:React 不支持 &lt;textarea&gt; 元素中的子元素。见https://reactjs.org/docs/forms.html#the-textarea-tag

如果您更改下面的文本区号,您将看到更新正确反映在 UI 中,并且稍后在您启用编辑时会很有用。

<textarea className="noteMain" value={Note} />

【讨论】:

  • 请注意,最好避免使用数组状态的索引值作为渲染元素列表的唯一键(在本例中为&lt;div&gt;),react.js 不会出于某种未知原因更改状态时,似乎无法很好地处理这种情况,我还没有弄清楚。
【解决方案2】:

将您的deleteNote 方法修改为:

deleteNote = (index) => {
    var noteList = this.state.Notes;
    alert(index);
    this.setState({ Notes:[...noteList.slice(0, index), ...noteList.slice(index + 1)] });
}

这是一个工作示例:https://codesandbox.io/s/serene-albattani-gymrx

【讨论】:

  • 这有同样的结果。它会删除警报显示正确索引的最后一个注释。
  • 在 Codepen 中尝试过,但最终删除了错误的元素。
  • 我添加了一个工作示例@briliston。你可以试试。
猜你喜欢
  • 2013-08-20
  • 1970-01-01
  • 1970-01-01
  • 2021-05-04
  • 1970-01-01
  • 2015-04-20
  • 2018-03-12
  • 2019-10-14
  • 1970-01-01
相关资源
最近更新 更多