React与Node.js开发中提交对象出现重复key的原因是什么?
问题成因&语法逻辑说明
这个问题本质是对ES6对象属性简写语法的使用误区,具体逻辑如下:
错误写法的嵌套原因
你最初写的 { username: {username}, password: {password} } 中,{username} 本身就是符合对象简写规则的写法,它等价于 { username: username }——也就是你给外层 username 这个键赋值了一个新对象,这个新对象的键也叫 username,值才是你从useState拿到的字符串变量。
所以最终生成的结构自然就是嵌套的 { username: { username: 'aa' }, password: { password: 'zz' } }。
正确写法的逻辑
你改后的 { username, password } 是标准的ES6对象属性简写用法:当对象的键名,和你要赋值的变量名完全一致时,可以省略冒号和值的书写,直接写变量名即可。
它完全等价于写全的写法:
const inputData = { username: username, password: password }
这里的 username、password 就是你用useState声明的字符串状态变量,所以最终生成的就是你预期的扁平结构 {username: 'aa', password: 'zz'}。
补充示例方便理解
我们可以用更简单的代码复现这个逻辑:
const fruit = 'apple' const price = 10 // 简写写法,等价于 {fruit: fruit, price: price} const normalObj = { fruit, price } console.log(normalObj) // 输出:{ fruit: 'apple', price: 10 } // 嵌套写法,等价于 {fruit: {fruit: fruit}, price: {price: price}} const nestedObj = { fruit: {fruit}, price: {price} } console.log(nestedObj) // 输出:{ fruit: { fruit: 'apple' }, price: { price: 10 } }
内容的提问来源于stack exchange,提问作者phershbe
相关产品推荐
相关产品推荐

