简体   繁体   English

即使在状态更改后,状态数组中动态映射的组件也不会更新

[英]Dynamically mapped components from array in state are not updating even after state changes

I'm mapping an array in the state to build dropdowns dynamically.我正在映射状态中的数组以动态构建下拉列表。 I have two working methods to add and remove values in the array.我有两种工作方法来添加和删除数组中的值。 When I remove and add values to the array I want the UI elements to also update as the state changes.当我删除数组并将值添加到数组时,我希望 UI 元素也随着状态的变化而更新。 Addition works but deletion fails every time.添加有效,但每次删除都失败。 I have confirmed the array in the state is being changed correctly but I can only ever delete the newest component instead of a specific one.我已经确认状态中的数组正在正确更改,但我只能删除最新的组件而不是特定的组件。 Thanks for your help.谢谢你的帮助。

 //
 handleToggle() {
    return this.state.AdditionQueryArray.map((array, index) => {
      let key = array.key;
      return (
        <div>
          <Select
            onChange={(e) => this.AdditionalOperatorHandleChange(e, key)}
            options={this.state.OperatorOptions}
            placeholder="Select Operator"
            menuPortalTarget={document.body}
            menuPosition={"fixed"}
          />
          <button onClick={() => this.deleteAdditonalQuery(index)}>
            Delete
          </button>
          {this.forceUpdate}
        </div>
      );
    });
  }

  createAdditionalQuery() {
    const state = this.state;

    let key = Math.random().toString(36).substring(7);

    var copyArr = [...this.state.AdditionQueryArray];

    copyArr.push({
      key: key,
      field: "fieldDefault",
      property: "propertyDefault",
      PropValue: "Propvalue",
    });
    this.setState({
      AdditionQueryArray: copyArr,
    });
  }

  deleteAdditonalQuery(indexVal) {
    var state = this.state;

    var copyArr = [...this.state.AdditionQueryArray];

    if (indexVal > -1) {
      copyArr.splice(indexVal, 1);
    }

    this.setState({
      AdditionQueryArray: copyArr,
    });
  }

  render() {
    return (
      <div>
        <button onClick={this.createAdditionalQuery}>Add Query </button>
        {this.handleToggle()}
      </div>
    );
  }
  ////

Shallow copy and array.splice is interesting way to remove an element from an array by index.浅拷贝和array.splice是通过索引从数组中删除元素的有趣方法。 I suggest using array.filter instead, it's much more clean.我建议改用array.filter ,它更干净。 I suggest always using functional state updates when updated arrays stored in state, especially when used in callbacks attached in loops.当更新的数组存储在状态中时,我建议始终使用功能状态更新,尤其是在循环中附加的回调中使用时。 This avoids any stale state enclosures.这避免了任何陈旧的状态外壳。

deleteAdditonalQuery(indexVal) {
  this.setState(prevState => ({
    AdditionQueryArray: prevState.AdditionQueryArray.filter(
      (el, index) => index !== indexVal
    ),
  }));
}

Similarly in the add handler, use a functional state update.同样在添加处理程序中,使用功能状态更新。

createAdditionalQuery() {
  this.setState(prevState => ({
    AdditionQueryArray: prevState.AdditionQueryArray.concat({
      key: Math.random().toString(36).substring(7),
      field: "fieldDefault",
      property: "propertyDefault",
      PropValue: "Propvalue",
    }),
  }));
}

In handleToggle remove the "dead" force update code, it shouldn't be necessary.handleToggle删除“死”强制更新代码,它应该没有必要。 It's not being invoked anyway.无论如何它都没有被调用。 Don't forget to add a React key to the outermost element being mapped.不要忘记向被映射的最外层元素添加一个 React 键。

handleToggle() {
  return this.state.AdditionQueryArray.map((array, index) => {
    const key = array.key;
    return (
      <div key={key}> // <-- add React key!
        <Select
          onChange={(e) => this.AdditionalOperatorHandleChange(e, key)}
          options={this.state.OperatorOptions}
          placeholder="Select Operator"
          menuPortalTarget={document.body}
          menuPosition={"fixed"}
        />
        <button onClick={() => this.deleteAdditonalQuery(index)}>
          Delete
        </button>
      </div>
    );
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 映射的状态数组不返回组件(ReactJS) - Mapped state array not returning components (ReactJS) State 更改后组件未更新 - Component Not Updating After State Changes 从映射组件收集所有状态并存储状态 - Collecting all state from mapped components and store state 如何在每个映射组件中更新组件 State 当一个更改时 - How to Update Component State in Each of Mapped Components When One Changes 热模块重新加载后,React组件未从Redux状态更新 - React components not updating from Redux state after Hot Module Reload 当组件位于数组内时,State 不会从 function 更新 - State is not updating from a function when the components are inside an array 为什么我映射的 function 需要提交两次才能在更新数组内容后显示更新的 state? - Why do I need to submit twice for my mapped function to display the updated state after updating the array content? 将选定状态设置为映射组件 - Setting Selected State to Mapped Components 为什么即使在 API 调用后状态发生变化,React 也不重新渲染组件 - Why React not re-rendering components even if it's state changes after an API call 如何更新从嵌套对象的状态数组映射的单个嵌套组件,而不重新渲染所有内容? - How to update individual nested components mapped from a state array of nested objects, without re-rendering everything?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM