【问题标题】:Add value from inputs to array if not exists如果不存在,则将输入中的值添加到数组
【发布时间】:2020-04-12 20:18:38
【问题描述】:

我在我的 React 应用程序中呈现一个 Array 并且对于每个 Array 我都有一个 input 元素。 此元素从数组条目中获取为nameID,并且可以输入一个值。

我有一个handleChange() 函数,它获取IDinput value

这个数据应该被添加到一个数组中,我想把它保存到我的State

稍后,我为每个 Array 条目设置了一个 Submit 按钮,我必须将输入值发送到 API 端点。

constructor(props: Props) {
    super(props);
    this.state = {
        sendTransferObj: []
    };
    this.handleChange = this.handleChange.bind(this);
}

...

handleChange(transId: string, event: React.ChangeEvent<HTMLInputElement>) {
    console.log(transId, event.target.value); // returns => '123', '1'

    let inputObject = [{ id: transId, value: event.target.value }]
    let arrayForState = [];

    const index = inputObject.findIndex(inputObject => inputObject.id != transId)

    if (index === -1) {
        arrayForState.push(inputObject);
    } else {
        console.log("object already exists")
    }

    console.log(arrayForState)

    this.setState({
        ...this.state,
        sendTransferObj: arrayForState
    }); // error!
}

...

<Form.Control as="input" name={trans.id} onChange={this.handleChange.bind(this, trans.id)} />

我的问题目前在我的handleChange() 中,其中输入值被保存到我的arrayForObject 以进行一个输入,但如果我在第二个输入元素中输入一个值,它会被覆盖。

当我稍后想要做一个setState() 来保存这个数组时,我也会遇到各种错误。

这是我用作参考的整个组件(获取我使用 Redux 从我的状态呈现的数组):https://codesandbox.io/s/practical-ptolemy-69zbu?fontsize=14&theme=dark

【问题讨论】:

    标签: javascript arrays reactjs typescript object


    【解决方案1】:

    您需要将 inputObject 附加到当前状态的 sendTransferObj 数组,而不是将其附加到新的空数组(这将导致覆盖)。你可以使用spread syntax

    handleChange(transId: string, event: React.ChangeEvent<HTMLInputElement>) {
        let inputObject = [{ id: transId, value: event.target.value }]
        const index = inputObject.findIndex(inputObject => inputObject.id != transId)
    
        this.setState({
            ...this.state,
            sendTransferObj: index === -1 ? [
              ...this.state.sendTransferObj,
              inputObject
            ] : this.state.sendTransferObj
        });
    }
    

    但是,当找到 inputObject 时,这不会更新该字段。我建议将值存储在 ID 作为键的对象中(并在请求 API 时将其格式化为所需的格式)。这样,您不必遍历数组来查找匹配的对象。

    
    constructor(props: Props) {
        super(props);
        this.state = {
            sendTransferObj: {}
        };
        this.handleChange = this.handleChange.bind(this);
    }
    
    ...
    
    handleChange(transId: string, event: React.ChangeEvent<HTMLInputElement>) {
          this.setState({
              ...this.state,
              sendTransferObj: {
                ...sendTransferObj,
                [transId]: event.target.value
              }
          }); 
      }
    

    【讨论】:

    • 感谢您抽出宝贵时间回答我的问题! @hbentlov 它可以工作,但剩下的唯一问题是,对于每个输入,它都会向值添加一个新对象:abload.de/img/screenshot2019-12-20a9fkkz.png
    • 所以如果我输入12例如,它应该是[{id: '123', value: 12}]而不是[{id: '123', value: 1}, {id: '123', value: 12}]的两个对象:)
    • 我更新了答案,建议使用对象而不是数组来存储值。
    猜你喜欢
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2018-05-04
    • 2021-08-30
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多