从行中删除下拉列表和文本字段会在 ReactJS 中的状态更改中删除不正确的字段

Removing dropdown and text field from row removes incorrect field on State Change in ReactJS

我有一行,其中包括一个 React-Select 下拉列表和一个输入字段。我正在尝试通过其索引删除特定行。我在我的处理程序函数中传递索引,并希望从行中删除这两个字段。输入字段已正确删除,但下拉列表值未从同一行中删除,并且它从最后一个索引中删除了下拉列表。

我将借助此处理程序中的索引删除该行

按索引删除行:

handleRemoveSocial(idx) {
    let someArray = this.state.SocialData;
    someArray.splice(idx, 1);
    this.setState({ SocialData: someArray });
  }

我在映射方法的帮助下呈现 Select 下拉列表和文本框,映射到我所在州的数组。现在,当我删除文本框时,如何从同一行映射 Select 下拉值。我在这个 post.

中包含了沙盒 link
{this.state.SocialData.map((Social, idx) => (
            <div className="form-group" key={idx}>
              <label htmlFor={"socialprofile"} className="control-label">
                Social profile
              </label>
              <div className="form-input-container select-social-link">
                <Select
                  data-id={idx}
                  className="profile-module-select-container"
                  classNamePrefix="profile-module-select"
                  options={options}
                  onChange={(selected) => {
                    this.handleSocialNameChange(selected.value, idx);
                  }}
                  onMenuOpen={() => {
                    this.setState({
                      selectMenuOpen: true
                    });
                  }}
                  onMenuClose={() => {
                    this.setState({
                      selectMenuOpen: false
                    });
                  }}
                  components={{
                    IndicatorSeparator: () => null
                  }}
                  placeholder={"Select"}
                  isSearchable={false}
                  isClearable={false}
                />
              </div>
              <div className="form-input-container input-social-link">
                <input
                  type="text"
                  id={`${SocialData[idx].socialname}-${idx}`}
                  className="social-form-control"
                  placeholder={`Social Url - ${Social.socialname}`}
                  value={SocialData[idx].name}
                  onChange={(e) =>
                    this.handleInputVlaueChange(e.target.value, idx)
                  }
                />

SANDBOX

您不能将 index 值设置为 key。这将在添加和删除元素时引起问题。 另外,不要使用 array.splice 使用 array.filter。 splice 将改变原始状态数组。

这是在此处触发 change 事件时 handleSocialNameChange() 处理程序中发生问题的地方。

onChange={(selected) => {
   this.handleSocialNameChange(selected.value, idx);
}}

使用索引作为 id 总体上不是一个好主意。因为他们后来把事情搞砸了,我们也必须在代码中添加额外的逻辑。

我们可以有效地使用 uuid() 库或技巧 new Date().getTime().toString() 来获取 ID。

CODESANDBOX的工作代码Link:

https://codesandbox.io/s/reasontosmile-n6ww4?file=/src/App.js

尽情享受吧:)