簡體   English   中英

在狀態react js中存儲和更新關聯數組

[英]store and update associative array in state react js

如何在鍵已經存在時更新我的​​關聯數組,否則我想創建一個新鍵並將該數組存儲在狀態中。 我曾試圖在關聯數組中存儲一個值。 當我在輸入字段中輸入數據時,可以調用handleChange之后我要執行上面提到的操作

    import React, { Component } from 'react';

        class App extends Component {
            constructor(props) {
                super(props);
                this.onChangeEvent = this.onChangeEvent.bind(this);
                this.onChangeCount = this.onChangeCount.bind(this);
                this.onSubmit = this.onSubmit.bind(this);
                this.state = {
                    name: [],
                    inputCount:5
                }
            }
// associtive array
        handleChange = (e) => {
// I want to check the key is already exist or not if exist means create update the value else create a new key and also I want to validate all the data.
                    const check = e.target.name
                    const value = e.target.value
                    const name = []
                    name[check] = value
                    console.log(name)
                    this.setState({
                        name,
                    })
            }
        render() {
                let options = []
                for (let i = 0; i < this.state.inputCount; i += 1) { options.push(i); }
            return (
{this.state.inputCount && (
                        options1.map((i) => {
                            return (<div key={i}>
                                <input  onChange={this.handleChange} type="text" className="name" name={`name${i}`} placeholder="Name" /><br />
                            </div>)
                        })
                    )}
        );
            }
        }
        export default App;

首先,盡管有對象,但JavaScript中沒有“關聯數組”,基本上是相同的。 因此,馬上,您應該將name的初始化更改為{}而不是[]

要檢查對象中是否存在鍵,只需check in obj甚至name.hasOwnProperty(check)中進行check ,其中check是要檢查的鍵。

設置和更新值的方式與JavaScript中的設置方法相同,無論鍵是否存在: name[check] = value

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM