简体   繁体   English

使用地图和索引es6更新嵌套数组的值

[英]Update nested array values using map and index es6

I have a react form which has dynamic rows, but I'm stuck at line 76 (Demo: https://codesandbox.io/s/pw58j0vzoq ), not sure what can I do to update the value in the row 我有一个具有动态行的React表单,但我停留在第76行(演示: https : //codesandbox.io/s/pw58j0vzoq ),不确定该如何更新行中的值

class App extends React.Component {
  state = {
    acceptedValues: [
      {
        id: 1,
        _arguments: ["Samsung", "xiaomi"]
      },
      {
        id: 2,
        _arguments: ["OR", "AND"]
      }
    ]
  };

  handleChange = (name, index, argumentIndex) => e => {
    const { acceptedValues } = this.state;
    if (name === "_arguments") {
      updatedState = acceptedValues.map((o, i) => {
        if (i === index) {
          return {
            ...o,
            _arguments: o._arguments.map((o2, index2) => {
              if (index2 === argumentIndex) {
                //what to do here?
              }
              return o;
            })
          };
        }
        return o;
      });
      this.setState({
        acceptedValues: updatedState
      });
    }
  };

  render() {
    const { acceptedValues } = this.state;
    return (
      <div>
        {acceptedValues.map(({ operator, _arguments }, index) => (
          <div style={{ marginBottom: 20 }}>

            <div>
              {_arguments.map((val, argumentIndex) => (
                <div>
                  <input
                    onChange={this.handleChange(
                      "_arguments",
                      index,
                      argumentIndex
                    )}
                    id="_arguments"
                    type="text"
                    value={val}
                  />
                  <button onClick={this.removeArgument(index, argumentIndex)}>
                    -
                  </button>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>
    );
  }
}

I'm able to navigate until the correct array but stuck at how to update the value within the array, I've 2 indexs in my handleChange function. 我能够导航到正确的数组,但是仍然坚持如何更新数组中的值,在handleChange函数中有2个handleChange

There you are mapping an array into another, so you should just pick which string to return, like this: 在那里,您正在将一个数组映射到另一个数组,因此您应该选择要返回的字符串,如下所示:

_arguments: o._arguments.map(
    (o2, index2) => {
        if (index2 === argumentIndex) return e.target.value
        return o2
    }
)

Or in an even cleaner way: 或更干净的方式:

_arguments: o._arguments.map(
    (o2, index2) => index2 === argumentIndex ? e.target.value : o2
)

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM