提交函数改变的反应表单状态
React form state mutated by submit function
我正在自学 React,并使用 Axios API 构建一个小型单页 React 应用程序。我有一个 POST 请求一直失败。 console.log
的广泛使用似乎表明提交功能以某种方式改变了表单输入的状态,但我不明白为什么。求助!
代码如下:
import React, { useState, useEffect } from 'react'
import axios from 'axios'
import { Grid, TextField, Button, Typography } from '@material-ui/core'
import { FaHome } from 'react-icons/fa'
const AddItem = ({ setShowAddItem }) => {
const [inputs, setInputs] = useState()
const [submitted, setSubmitted] = useState(false)
useEffect(() => {
console.log(`Type: ${typeof inputs} Data: ${inputs}`)
if (inputs) {
console.log('executing POST')
console.log(`Inside if() Type: ${typeof inputs} Data: ${inputs}`)
axios.post('/api/ItemModels', { ...inputs })
.then(res => {
console.log(res.data)
})
.catch(err => console.error(err))
setInputs()
setSubmitted(false)
}
}, [submitted])
const handleInputChange = event => {
setInputs({ ...inputs, [event.target.name]: event.target.value })
console.log(inputs)
console.log(typeof inputs)
}
const handleSubmit = event => {
console.log("handleSubmit triggered")
if (event) {
console.log("if() in handleSubmit triggered")
console.log(`Inside handleSubmit Data: ${inputs}`)
event.preventDefault()
setSubmitted(true)
}
}
return (
<>
<Grid container className="form-container">
<Typography variant="h3">Add an Item</Typography>
<form noValidate onSubmit={handleSubmit}>
<TextField name="shape" label="Shape" onChange={handleInputChange} required />
<TextField name="size" label="Size" onChange={handleInputChange} required />
<TextField name="color" label="Color" onChange={handleInputChange} required />
<TextField name="clarity" label="Clarity" onChange={handleInputChange} required />
<TextField name="price" label="Price" onChange={handleInputChange} required />
<TextField name="listPrice" label="List Price" onChange={handleInputChange} required />
<Button type="submit">
Submit
</Button>
</form>
</Grid>
<Button type="button" onClick={() => setShowAddItem(false)}>
<FaHome />
</Button>
</>
)
}
export default AddItem
这是 CodeSandbox 的 link(可能与这里的有所不同,因为我玩过不同的东西):CodeSandbox
这是我最近尝试的控制台副本:
// the last console.log from handleInputChange shows an Object with the right data
object // <= that's the typeof from handleInputChange
handleSubmit triggered
Inside handleSubmit Data: [object Object]
if() in handleSubmit triggered
Inside handleSubmit if() Data: [object Object]
Type: object Data: [object Object] // <= from useEffect
executing POST
Inside if() Type: object Data: [object Object]
Type: undefined Data: undefined // <= useEffect triggered by setSubmitted(false)
Error: "Request failed with status code 400"
日志似乎表明 inputs
状态在 handleSubmit 函数中从正常的 JavaScript 对象变为 [object Object],甚至在 if()
[=44= 之前] preventDefault()
被调用,虽然我不明白为什么。这里再次显示 handleSubmit()
的代码:
const handleSubmit = event => {
console.log("handleSubmit triggered")
console.log(`Inside handleSubmit Data: ${inputs}`)
if (event) {
console.log("if() in handleSubmit triggered")
console.log(`Inside handleSubmit if() Data: ${inputs}`)
event.preventDefault()
setSubmitted(true)
}
}
我可能应该强调一下,我是编程的新手,而且我不得不自学很多东西,所以我很害怕在某个地方出现明显的错误。尽管如此,我还是花了几个小时来研究这个,甚至打电话给一个 React 开发人员的朋友,他也被难住了。我试过研究 handleSubmit
的调用方式,将其放入按钮中,或通过 onSubmit
的箭头函数返回它。我也试过在 preventDefault
周围移动。似乎没有任何帮助。
我不认为这与 Axios 有什么关系,因为 inputs
在他们到达 POST 请求时已经 undefined
,但我输入axios作为标签希望这可能是面向axios的程序员所熟悉的bug。
同样,通过 Postman 发出 POST 请求非常有效。
最后一件事:该项目的后端是 .NET,所以我正在 Visual Studio 上开发。我认为这可能是一些错误的 Visual Studio 行为,但是 运行 CodeSandbox 中的代码产生了相同的错误,所以除非它是一些奇怪的格式化错误,否则它似乎是别的东西,以我的谦虚和没有受过教育的意见。
有什么想法吗?
这是解决问题的评论摘要:
像下面这样将对象传递到 console.log()
的字符串中总是会导致显示 [object Object]
,因为将其转换为字符串会导致怀疑对象属性在实际存在时发生了变化.
console.log(`Type: ${typeof inputs} Data: ${inputs}`);
相反,使用第二个参数或进行单独的日志调用:
console.log(`Type: ${typeof inputs} Data:`, inputs);
之后是更正 POST 数据属性以确保大小写和类型与后端匹配 API。
我正在自学 React,并使用 Axios API 构建一个小型单页 React 应用程序。我有一个 POST 请求一直失败。 console.log
的广泛使用似乎表明提交功能以某种方式改变了表单输入的状态,但我不明白为什么。求助!
代码如下:
import React, { useState, useEffect } from 'react'
import axios from 'axios'
import { Grid, TextField, Button, Typography } from '@material-ui/core'
import { FaHome } from 'react-icons/fa'
const AddItem = ({ setShowAddItem }) => {
const [inputs, setInputs] = useState()
const [submitted, setSubmitted] = useState(false)
useEffect(() => {
console.log(`Type: ${typeof inputs} Data: ${inputs}`)
if (inputs) {
console.log('executing POST')
console.log(`Inside if() Type: ${typeof inputs} Data: ${inputs}`)
axios.post('/api/ItemModels', { ...inputs })
.then(res => {
console.log(res.data)
})
.catch(err => console.error(err))
setInputs()
setSubmitted(false)
}
}, [submitted])
const handleInputChange = event => {
setInputs({ ...inputs, [event.target.name]: event.target.value })
console.log(inputs)
console.log(typeof inputs)
}
const handleSubmit = event => {
console.log("handleSubmit triggered")
if (event) {
console.log("if() in handleSubmit triggered")
console.log(`Inside handleSubmit Data: ${inputs}`)
event.preventDefault()
setSubmitted(true)
}
}
return (
<>
<Grid container className="form-container">
<Typography variant="h3">Add an Item</Typography>
<form noValidate onSubmit={handleSubmit}>
<TextField name="shape" label="Shape" onChange={handleInputChange} required />
<TextField name="size" label="Size" onChange={handleInputChange} required />
<TextField name="color" label="Color" onChange={handleInputChange} required />
<TextField name="clarity" label="Clarity" onChange={handleInputChange} required />
<TextField name="price" label="Price" onChange={handleInputChange} required />
<TextField name="listPrice" label="List Price" onChange={handleInputChange} required />
<Button type="submit">
Submit
</Button>
</form>
</Grid>
<Button type="button" onClick={() => setShowAddItem(false)}>
<FaHome />
</Button>
</>
)
}
export default AddItem
这是 CodeSandbox 的 link(可能与这里的有所不同,因为我玩过不同的东西):CodeSandbox
这是我最近尝试的控制台副本:
// the last console.log from handleInputChange shows an Object with the right data
object // <= that's the typeof from handleInputChange
handleSubmit triggered
Inside handleSubmit Data: [object Object]
if() in handleSubmit triggered
Inside handleSubmit if() Data: [object Object]
Type: object Data: [object Object] // <= from useEffect
executing POST
Inside if() Type: object Data: [object Object]
Type: undefined Data: undefined // <= useEffect triggered by setSubmitted(false)
Error: "Request failed with status code 400"
日志似乎表明 inputs
状态在 handleSubmit 函数中从正常的 JavaScript 对象变为 [object Object],甚至在 if()
[=44= 之前] preventDefault()
被调用,虽然我不明白为什么。这里再次显示 handleSubmit()
的代码:
const handleSubmit = event => {
console.log("handleSubmit triggered")
console.log(`Inside handleSubmit Data: ${inputs}`)
if (event) {
console.log("if() in handleSubmit triggered")
console.log(`Inside handleSubmit if() Data: ${inputs}`)
event.preventDefault()
setSubmitted(true)
}
}
我可能应该强调一下,我是编程的新手,而且我不得不自学很多东西,所以我很害怕在某个地方出现明显的错误。尽管如此,我还是花了几个小时来研究这个,甚至打电话给一个 React 开发人员的朋友,他也被难住了。我试过研究 handleSubmit
的调用方式,将其放入按钮中,或通过 onSubmit
的箭头函数返回它。我也试过在 preventDefault
周围移动。似乎没有任何帮助。
我不认为这与 Axios 有什么关系,因为 inputs
在他们到达 POST 请求时已经 undefined
,但我输入axios作为标签希望这可能是面向axios的程序员所熟悉的bug。
同样,通过 Postman 发出 POST 请求非常有效。
最后一件事:该项目的后端是 .NET,所以我正在 Visual Studio 上开发。我认为这可能是一些错误的 Visual Studio 行为,但是 运行 CodeSandbox 中的代码产生了相同的错误,所以除非它是一些奇怪的格式化错误,否则它似乎是别的东西,以我的谦虚和没有受过教育的意见。
有什么想法吗?
这是解决问题的评论摘要:
像下面这样将对象传递到 console.log()
的字符串中总是会导致显示 [object Object]
,因为将其转换为字符串会导致怀疑对象属性在实际存在时发生了变化.
console.log(`Type: ${typeof inputs} Data: ${inputs}`);
相反,使用第二个参数或进行单独的日志调用:
console.log(`Type: ${typeof inputs} Data:`, inputs);
之后是更正 POST 数据属性以确保大小写和类型与后端匹配 API。