Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
83 views
in Technique[技术] by (71.8m points)

javascript - Is it possible to use dynamic object keys in useState in Reactjs?

I'm trying to get the data from a form in which some fields are dynamic so that their names follow a pattern like the days of the week ending in 1 or 2.
In the onChange I send the name of the component that I am editing so the program knows what input is being edited but when I use the name that I send by parameter in the useState it does not detect it as the variable but as a normal string.

const [horas, setHoras] = useState({});  

const handleHoras = (e: any, nomb: string) => {
        setHoras({
            ...horas,
            nomb: e.target.value
        })
    }

Ive tried to declare the state as an array (as I show below) but the variable is not overwriting itself but adding variables with the same name every time the value changes.


    const handleHoras = (e: any, nomb: any) => {
        setHoras(
            [
                ...horas,
                { 'name': nomb, 'value': e.target.value }
            ]
        )
    }

question from:https://stackoverflow.com/questions/65945083/is-it-possible-to-use-dynamic-object-keys-in-usestate-in-reactjs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I assume you are looking for dynamic object keys? If yes - with ES6 you could use { [key]: value } syntax


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...